在Vue中将echart封装为可复用组件

首先在项目中安装echarts
npm install echarts --save

1.动态设置id。为什么是动态,id是唯一的,这不用多说吧。

<template>
  <div id="pieChart">
    <div :id="echarts" class="echarts" ref="echarts" style="width: 500px;height: 300px;"></div>
  </div>
</template>

2.引入echarts
const echarts = require('echarts')
3.上面说过了id是唯一的,使用echarts.init这个方法来创建一个 ECharts 实例,返回 echartinstance,不能在单个容器上初始化多个 ECharts 实例,因此需要用到Vue的computed属性来解决这个问题

computed: {
    echarts () {
      return 'echarts' + Math.random()*100000
    }
  }

4.因为把它封装成了一个Vue组件,父子组件之间的通信需要用到props这个属性

props: {
    // 接收父组件传递过来的信息
    chartData: {
      type: Object,  //此处可以为Array或者Object或者其它,根据需求来。
      default: ()=>[]
    }
  }

5.封装echarts。

methods: {
    drawChart () {
      const that = this
      let myChart = echarts.init(document.getElementById(that.echarts))
      let option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "horizontal",
          left: "center",
          bottom: 2,
          data: that.chartData.legend
        },
        // #7498f7 蓝色 #eec557 黄色 #f3655d 红色 #44e9a7 绿色
        color: ['#7498f7', 'sandybrown', '#f3655d'],
        series: [
          {
            name: that.chartData.titles,
            type: "pie",
            radius: "55%",
            // 动态获取data
            data: that.chartData.data1,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      }
      // 清除画布
      myChart.clear()
      myChart.setOption(option)
      // 在渲染点击事件之前先清除点击事件
      myChart.off('click')
    }
  }

6.在Vue的生命周期mounted执行,并且在this.$nextTick里面执行这个方法,保证承若所有的子组件被挂载、能保证通过获取到组件

mounted () {
    const that = this
    that.$nextTick(()=> {
      console.log(that.chartData)
      that.drawChart()
    })
  }

注意:
在父组件中调用子组件,如果是通过ajax获取的数据,需要在引入组件是判断一下数组或对象是否为空。

<nestingPic :chartData='receivableAccepted' v-if='receivableAccepted.length > 0' />
4148329-110b45c873bfa11d.png
3.png
4148329-6b3d7832224fa4ee.png
2.png

猜你喜欢

转载自blog.csdn.net/weixin_33991418/article/details/87216814
今日推荐