Ssanbei101小优化
5e4abd4c创建于 2025年3月26日历史提交
<template>
  <div class="container" ref="container">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>
  
<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from 'vue';
import * as echarts from 'echarts';
import { type ECharts } from 'echarts'
import { useElementSize } from '@vueuse/core';

const chartInitialized = ref(false);
const myChart = ref<ECharts | null>(null);
const container = useTemplateRef('container');
const chartRef = useTemplateRef('chartRef');

const initializeChart = async () =>{
  await nextTick();
  if (!chartRef.value || !container.value) {
    console.warn("图表元素不可用,无法初始化");
    return;
  }
  try {
    myChart.value = echarts.init(chartRef.value);
    const option = {
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar'
        }
      ]
    };
    myChart.value.setOption(option);
    chartInitialized.value = true;
  } catch (error) {
    console.error("初始化图表时出错:", error);
  }
}

onMounted(async () => {
  setTimeout(() => {
    initializeChart();
  }, 100);
});

onBeforeUnmount(() => {
  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }
});

const { width, height } = useElementSize(container);

watch([width, height], ([newWidth, newHeight]) => {
  console.log('容器尺寸变化:', newWidth, 'x', newHeight);
  if (chartInitialized.value && myChart.value) {
    // 已初始化的图表只需要调整大小
    myChart.value.resize();
  } else if (newWidth > 0 && newHeight > 0) {
    // 仅在容器有尺寸且图表未初始化时初始化
    initializeChart();
  }
}, { immediate: false });
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 100px;
}
</style>