Vue中封装Echart

314 阅读1分钟

<template>
  <div :id="id" :data="data" class="echart-concent"></div>
</template>

<script>
import echarts from 'echarts'
import { debounce } from 'lodash'
export default {
  name: "theGraph",
  props: {
    id: String,
    data: Object
  },
  computed: {
    // // 用来获取和更新组件外部的值
    // imgValue: {
    //     get() {
    //         return this.img;
    //     },
    //     set(newVal) {
    //         this.$emit("setImg", newVal, this.index);
    //     },
    // },
  },
  data() {
    return {
      chartLineGraph: null,
    };
  },
  // 侦听器
  watch: {
    data: {
      deep: true,
      handler(newValue, oldValue) {
        // console.log(newValue);
        this.drawLineGraph(this.id, newValue);
      },
    },
  },
  methods: {
    drawLineGraph(id, data, resetData) {
      // 再实例化之前判断防止Echart的空数据状态报错
      if (
        this.chartLineGraph != null &&
        this.chartLineGraph != "" &&
        this.chartLineGraph != undefined
      ) {
        this.chartLineGraph.dispose();
      }

      let eChart = document.getElementById(id)
      this.chartLineGraph = echarts.init(eChart)
      this.chartLineGraph.setOption(data)
    },
  },
  created() { },
  mounted() {
    this.drawLineGraph(this.id, this.data);
    this.resizeHandler = debounce(() => {
      if (this.chartLineGraph) {
        this.chartLineGraph.resize()
      }
    }, 100)
    window.addEventListener('resize', this.resizeHandler)
  },
  beforeDestroy() {
    // 防止Echart的空数据状态报错
    if (this.chartLineGraph) {
      this.chartLineGraph.clear();
    }
  },
};
</script>

<style lang="scss" scoped>
.echart-concent {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  ::v-deep {
    canvas {
      width: 100% !important;
      height: 100% !important;
    }
  }
}
</style>