Vue-cli中使用echarts

2019-12-03  本文已影响0人  Gino_Li

npm包选择:

推荐使用echarts,不推荐使用vue-echarts(更新慢等问题)。

npm i echarts

使用方式:

步骤:

一.封装(echartsMixin.js )

1.引入echarts

import echarts from 'echarts';

2.echarts配置option,以柱状图为例

注意:代码必须写在computed中,写在data中的话echarts不会响应数据改变,因为mixin实例比引入的组件早,所以会先拿到data里的初始数据

computed: {
  option() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器,坐标轴触发有效
            type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: this.timeCompareAxis,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel:{
            'interval':0,
            rotate:20
          },
        }],
        yAxis: [{
          type: 'value',
        }],
        series: [{
          type: 'bar',
          barWidth: '60%',
          data: this.timeCompareChartData,
          label: {
            normal: {
              show: true,
              position: 'top'
            }
          }
        }]
      }
    }
}
3.变量
  data() {
    return {
      timeCompareChartData: [],
      timeCompareAxis: []
    }
  }
4.写一个实例化echarts的方法
methods: {
    drawChart(options, _id, isBar) {
      let _this = this;
      if (document.getElementById(_id)) {
        let chartInstance = echarts.init(document.getElementById(_id));
        chartInstance.setOption(options)
        chartInstance.resize();
        //根据窗口的大小变动图表(自适应)
        window.addEventListener('resize', () => {
          chartInstance.resize();
        })
     }
   }
}

二.调用(app.vue)

结构样式
<div class="chartbox">
  <div id="chart1" class="echarts"></div>
</div>
.chartbox {
    //必须外面套一个盒子给宽高
    width: 100%;
    height: 200px;
    .echarts {
      width: 100%;
      height: 100%;
    }
}
import echartsMixin from "@/mixins/echartsMixin"
export default {
  mixins: [echartsMixin],
  methods: {
      getHandleTotal(params) {
         //请求数据
        this.$get(XXX,params).then(res => {
        //数据处理
        res.forEach(val => {
            this.timeCompareChartData.push(val.data);
            timeCompareAxis.push(val.axis);
        })
      }).then(()=>{
      //实例化echarts,必须异步执行
        this.drawChart(this.option, "chart1", true);
      });
  }
}

大功告成

上一篇下一篇

猜你喜欢

热点阅读