美文网首页
(Vue) 在 main.js 中引入 echarts

(Vue) 在 main.js 中引入 echarts

作者: 斐硕人 | 来源:发表于2019-04-09 10:47 被阅读0次

需求:

在main.js中 引入echarts,免去在每个组件中引入的重复性工作

尝试解决

.vue 组件内

mounted() {
    this.initCharts()
  },
  methods: {
    initCharts() {
      this.chart = echarts.init(document.getElementById('id'))   //注意此处
      this.setOptions()
    },
    setOptions() {
      this.chart.setOption({
        title: {},
        tooltip: {},
        xAxis: {},
        yAxis: {},
        series: []
      })
    }

main.js

import echarts from 'echarts'

报错:

控制台显示 echarts is not defined

echarts is not defined

最终解决方案

main.js

import echarts from 'echarts'

Object.defineProperties(Vue.prototype, {
  echarts: { get: () => echarts }
});

.vue文件中

    initCharts() {
      this.chart = this.echarts.init(document.getElementById('id'))   // this.echarts 调用
      this.setOptions()
    },

参考:关于在main.js中引入文件的问题

原理

Vue 核心之数据劫持
vue.js关于Object.defineProperty的利用原理

相关文章

网友评论

      本文标题:(Vue) 在 main.js 中引入 echarts

      本文链接:https://www.haomeiwen.com/subject/nhoviqtx.html