Bootstrap

封装Echarts组件,实现窗口大小改变自适应,监听图表渲染结束

封装Echarts组件,实现窗口大小改变自适应,监听图表渲染结束事件

<template>
  <div class="chart" :ref="ref">
  </div>
</template>

<script>
import initEcharts from 'ecarts'
export default {
  name: 'Echart',
  props: {
  // 传入的配置项
    options: {
      type: Object,
      default() {
        return {}
      }
    },
    // 渲染完成的图表下标
    indexSign:{
      type: Number,
      default: -1
    },
    // 是否去记载图表渲染事件
    finished: {
      type: Boolean,
      default: false
    },
    // 获取DOM
    ref: {
      type: String,
      default: 'chart'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    options: {
      immediate: true,
      handler(val) {
        // 第二次传值 不重新加载实例,直接配置图表
        if (this.chart && this.refs.chart) {
          this.chart.setOption(val || {}, true)
        } else {
          initEcharts().then(echarts => {
            this.$nextTick(() => {
              this.chart = echarts.init(this.$refs.charts)
              this.chart.setOption(val || {}, true)
              // 添加浏览器窗口大小改变事件
              window.addEventListener('resize', () => {
                this.chart.resize()
              })
              if (this.finished && this.indexSign !== -1) {
                const promise = new Promise((resolve, reject) => {
                  this.chart.on('finished', ()=> {
                    // 让finished方法只执行一次
                    resolve()
                  })
                })
                promise.then(() => {
                  this.$emit('finishedHandle', this.chart, this.indexSign)
                })
              }
              // 添加图表点击事件
              this.chart.off('click')
              this.chart.on('click', (params) => {
                this.$emit('getParams', params)
                // 阻止时间冒泡
                params.event.event.stopPropagation()
              })
            })
          })
        }
      }
    }
  },
  beforeDestroy() {
    this.chart.clear()
    this.chart.dispose()
  },
}
</script>
;