<!--
    echart组件
    @author 刘梦祥
    @date 2023年2月9日
-->
<template>
  <div name="mechart" ref="mechart" class="mechart"></div>
</template>
<script>
export default {
  props: {
    option: Object
  },
  data() {
    return {
      myChart: ""
    };
  },
  computed: {
    watchOptionStr() {
      let a = this.option;
      return JSON.stringify(a);
    }
  },
  watch: {
    watchOptionStr: {
      handler: function(val, oldVal) {
        if (val !== oldVal && this.myChart) {
          this.myChart.setOption(this.option, true);
        }
      }
    }
  },
  mounted() {
    window.addEventListener("resize", this.resizeChart);
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeChart);
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
  methods: {
    resizeChart() {
      if (this.myChart !== "") {
        this.myChart.resize();
      }
    },
    initChart() {
      this.myChart = this.$echarts.init(this.$refs.mechart);
      if (this.option) {
        this.myChart.setOption(this.option);
      }
    }
  }
};
</script>
<style lang="less" scoped>
.mechart {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
