ECharts

162 阅读1分钟

Webpack项目中引入Echarts

npm install echarts -D

全局引用

入口文件 index.js

//引入echarts
import echarts from 'echarts'
Vue.prototype.$echarts = echarts;

vue文件中使用

    data(){
      return {
        chart: null
      }
    },
    beforeDestroy(){
      //组件销毁前销毁echart
      if(!this.chart){
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      //初始化
      initCircle(){
        this.chart = this.$echarts.init(document.getElementById('lineDiv'));
        const option = {
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          }]
        };
        this.chart.setOption(option);
        //大小随窗口自动变化
        window.onresize = this.chart.resize;
      }
    },
    mounted() {
      this.initCircle();
    }

这样打包后文件比较大,没有按需加载。

按需加载

在对应vue文件中

    const echarts = require('echarts/lib/echarts');
    require("echarts/lib/chart/line");
    require("echarts/lib/chart/bar");
  export default {
    name: "drawLine",
    data(){
      return {
        myChart: ''
      }
    },
    beforeDestroy(){
      if(!this.myChart){
        return;
      }
      this.myChart.dispose();
      this.myChart = null;
    },
    methods: {
      initCircle(){
        this.myChart = echarts.init(document.getElementById('lineDiv'));
        const option = {
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          }]
        };
        this.myChart.setOption(option);
        window.onresize = this.myChart.resize;
      }
    },
    mounted() {
      this.initCircle();
    }
  }

按需加载列表:
github.com/apache/incu…