<!--
 * @Author: zk
 * @Date: 2021-09-16 16:24:53
 * @LastEditTime: 2021-09-28 14:43:06
 * @LastEditors: Please set LastEditors
 * @Description: 柱状图
 * @FilePath: \vue-admin-template-master\src\layout\components\Echarts\commonChartsBar.vue
-->
<template>
  <div
    style="height: 100%; width: 100%; position: absolute; left: 0; top: 0"
    class="ChartsBar"
    :id="id"
  ></div>
</template>

<script>
import { markRaw } from "vue";
import * as echarts from "echarts";
import * as _ from "lodash";
// 柱状图初始数据
export default {
  name: "ChartsBar",
  props: {
    // 柱状图生成所需id
    id: {
      type: String,
      default: "",
    },
    // 柱状图额外的数据
    option: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      myChart: null, //柱状图实例
      desc: 300, // 防抖时间
    };
  },
  mounted() {
    // 柱状图dom
    const chartDom = document.getElementById(this.id);
    // 柱状图初始化
    this.myChart = markRaw(echarts.init(chartDom));
    // 生成柱状图
    this.myChart.setOption(_.cloneDeep(this.option));
    // 监听页面缩放 防止dom重复渲染
    window.addEventListener("resize", _.debounce(this.handle, this.desc));
  },
  watch: {
    // 监听数据变化，重绘折线图
    option: {
      deep: true,
      handler(newVal) {
        const chartDom = document.getElementById(this.id);
        // 先移除之前的实例，保证重绘的流畅性
        chartDom.removeAttribute("_echarts_instance_");
        this.myChart = markRaw(echarts.init(chartDom));
        this.myChart.setOption(_.cloneDeep(newVal));
      },
    },
  },
  destroyed() {
    // 销毁实例和移除监听
    this.myChart.dispose();
    window.removeEventListener("resize", this.handle);
  },
  methods: {
    /**
     * @description: 图形缩放
     * @param {*}
     * @return {*}
     */
    handle() {
      this.myChart.resize();
    },
  },
};
</script>
