<template>
  <div ref="echartsDom" class="echarts-warp"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'Echarts',
  props: {
    options: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      myChart: null
    };
  },
  mounted() {
    this.echartsInit();
    window.addEventListener('resize', this.echartsResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.echartsResize);
    if (this.myChart) {
      this.myChart.dispose(); // 清理图表实例，避免内存泄漏
    }
  },
  methods: {
    echartsInit() {
      if (this.$refs.echartsDom) {
        this.myChart = echarts.init(this.$refs.echartsDom);
        this.setEchartsOption();
      }
    },
    setEchartsOption() {
      if (this.myChart && this.options) {
        this.myChart.setOption(this.options, true);
      }
    },
    echartsResize() {
      if (this.myChart) {
        this.myChart.resize();
      }
    }
  },
  watch: {
    options: {
      handler(newOptions) {
        if (newOptions) {
          this.$nextTick(() => {
            this.setEchartsOption();
          });
        }
      },
      immediate: true,
      deep: true
    }
  }
};
</script>

<style scoped>
.echarts-warp {
  width: 100%;
  /* height: 100%; */
  height: 400px;
}
</style>
