1、Vue.js中封装Echarts图表组件

封装Echarts子组件,父组件可以多次调用

<template>
  <div :class="className" :id="id" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '200px'
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  watch: {
    chartData: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        if (this.chart) {
          if (newVal) {
            this.setOption(newVal)
          } else {
            this.setOption(oldVal)
          }
        }
      }
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id), 'macarons')
      this.setOption(this.chartData)
    },
    setOption(option) {
      this.chart.setOption({
        xAxis: {
          data: this.chartData.xAxis.data,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          data: this.chartData.legend.data
        },
        series: [
          {
            name: this.chartData.series[0].name,
            type: this.chartData.series[0].type,
            data: this.chartData.series[0].data,
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>

2、父组件向子组件传值

<bar-chart v-if="chartFlag" :id="'mybarchart'" :height="'300px'" :chart-data="chartData"></bar-chart>

chartData: {
        xAxis: {
          data: ['星期一', '星期二', '星期三', '星期四', '星期五']
        },
        legend: {
          data: ['123']
        },
        series: [
          {
            name: '123',
            type: 'bar',
            data: [11, 22, 33, 44, 55]
          }
        ]
      }

3、子组件监听数据变化,更新图表

watch: {
    chartData: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        if (this.chart) {
          if (newVal) {
            this.setOption(newVal)
          } else {
            this.setOption(oldVal)
          }
        }
      }
    }
  },
 
 

转自:https://www.jianshu.com/p/642d0dfa3ae1