PieChart.vue 2.61 KB
<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    option: {
      type: Object,
      default: () => {}
    },
    optionData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    option: {
      handler(newVal) {
        console.log('获取配置', newVal)
        if (this.chart) {
          this.setOption()
        }
      },
      immediate: true,
      deep: true
    },
    optionData: {
      handler(newVal) {
        console.log('获取数据', newVal)
        if (this.chart) {
          this.initData()
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: []
        },
        calculable: true,
        series: [
          {
            type: 'pie',
            center: ['50%', '50%'],
            data: [],
            animationEasing: 'cubicInOut',
            animationDuration: 2000
          }
        ]
      }
      this.chart.setOption(option)
      if (Object.keys(this.option).length > 0) {
        this.setOption()
      }
      if (this.optionData.length > 0) {
        this.initData()
      }
    },
    initData() {
      const legendData = []
      const seriesData = []
      this.optionData.forEach(item => {
        legendData.push(item.name)
        seriesData.push(item)
      })
      const option = {
        legend: {
          data: legendData
        },
        series: [
          {
            data: seriesData
          }
        ]
      }
      this.chart.setOption(option)
    },
    setOption() {
      this.chart.setOption(this.option)
    }
  }
}
</script>