Echarts组件封装

134 阅读1分钟

1.在compontens下新建文件BaseChart/index.vue

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

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resizeChart from '@/utils/mixins/risizeChart'

export default {
  mixins: [resizeChart],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    option: {
      type: Object,
      default: function () {
        return {}
      }
    },
    load: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      if (this.load) {
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption(this.option)
      }
    },
    destroyChart() {
      if (!this.load) {
        this.chart && this.chart.dispose()
      }
    }
  },
  watch: {
    load() {
      this.destroyChart()
      this.initChart()
    },
    option: {
      deep: true,
      handler(val) {
        this.destroyChart()
        this.initChart()
      }
    }
  }
}
</script>

2.引入到要使用的组件中进行使用