前端开发那些事儿vue 随手记

Vue 引入echarts 基础使用

2021-05-21  本文已影响0人  black墨

安装echarts

通过 npm 获取 echarts,npm install echarts --save

全局引用

为了省事,全局引用echarts
打开main.js 文件

import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts

echarts 新版本跟之前import 方式不一样了,需要as 一下。
放到全局就不用来回引用了,使用时候直接this.$echarts就可以。

使用

从echart 官网上面扒拉下来第一个例子,修改一下

<template>
  <div ref="testLine" id="testLine" style="width:600px; height:300px"></div>
</template>

<script>
export default {
  name: 'DisplayDraw',
  data () {
    return {
      myChart: null,
      option: {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [150, 230, 224, 218, 135, 147, 260],
          type: 'line'
        }]
      }
    }
  },
  methods: {
    initChart () {
      const {
        myChart,
        option
      } = this
      myChart.setOption(option)
    }
  },
  mounted () {
    // 两张引入方式都可以,这里我用ref,注意一定要节点 初始化完成
    // this.myChart = this.$echarts.init(document.getElementById('testLine'))
    this.myChart = this.$echarts.init(this.$refs.testLine)
    this.initChart()
  }
}
</script>

<style>
</style>

最后初始化这个myChart的时候,一定不要放到create 事件里面,因为界面没有初始化完成,啥都加载不出来

效果图

图片.png
上一篇 下一篇

猜你喜欢

热点阅读