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

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

export default {
  name: 'Charts',
  props: {
    // 图表数据
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chartInstance: null
    };
  },
  mounted() {
    this.createChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    /**
     * 绘制图表
     */
    createChart() {
      this.chartInstance = echarts.init(this.$refs.chart);
      this.chartInstance.setOption(this.options);
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  },
  watch: {
    options: {
      handler: function (newOptions) {
        if (this.chartInstance) {
          this.chartInstance.setOption(newOptions);
        }
      },
      deep: true,
      immediate: true
    }
  }
};
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
