vue中使用echarts

158 阅读1分钟

最近项目中需要使用echarts 记录一下. 首先需要下包然后挂载vue的原型

import * as echarts from 'echarts'
// 挂载到实例上
Vue.prototype.$echarts = echarts

然后在组件中使用,这里我使用的官方的折线图例子

//html
<div ref="myChart" id="main" style="width: 100%;height:400px;"></div>
</div>
//script
  mounted () {
    this.setMyEchart() // 页面挂载完成后执行
  },
  methods: {
    setMyEchart () {
      console.log(this.$echarts)
      const myChart = this.$refs.myChart // 通过ref获取到DOM节点
      if (myChart) {
        const thisChart = this.$echarts.init(myChart) // 利用原型调取Echarts的初始化方法
        // 配置
        const option = {
          xAxis: {
            data: ['A', 'B', 'C', 'D', 'E']
          },
          yAxis: {},
          series: [
            {
              data: [10, 22, 28, 23, 19],
              type: 'line',
              smooth: true
            }
          ]
        } // {}内写需要图表的各种配置,可以在官方案例中修改完毕后复制过来
        thisChart.setOption(option) // 将编写好的配置项挂载到Echarts上
        window.addEventListener('resize', function () {
          thisChart.resize() // 页面大小变化后Echarts也更改大小
        })
      }
    }
  }

效果

image.png 参考: (55条消息) [已解决] vue 引入 echarts 报init undefined问题_Synnny的博客-CSDN博客

前端深入之Vue篇 丨如何在项目中优雅的使用Echarts(上) - 掘金 (juejin.cn)