一个echarts+vue3饼图demo

112 阅读1分钟
<template>
   <div class="w-500px h-500px" ref="chartDom"></div>
</template>

<script setup>
import * as echarts from "echarts";

const chartDom = ref();
let chartInstance;

const debounce = (fn, delay = 200) => {
  let timeoutId;
  return () => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...arguments), delay);
  };
};

onMounted(async () => {
  await nextTick(); // 确保 DOM 更新完成

  try {
    chartInstance = echarts.init(chartDom.value);
    const option = {
      title: {
        text: "Distribution of Entities in CL160-ProFiler™",
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "horizontal", // 图例方向
        bottom: "bottom", // 图例距离底部位置
      },
      series: [
        {
          type: "pie",
          radius: "50%",
          data: [
            { value: 20, name: "Lung" },
            { value: 15, name: "Leukemia" },
            { value: 18, name: "Breast" },
            { value: 12, name: "Brain" },
            { value: 10, name: "Pancreas" },
            { value: 8, name: "Skin" },
            { value: 7, name: "Ovary" },
          ],
        },
      ],
    };
    chartInstance.setOption(option);

    // 设置窗口大小变化的事件监听器
    window.onresize = debounce(() => {
      chartInstance.resize();
    });
  } catch (error) {
    console.error("初始化图表失败:", error);
  }
});

onUnmounted(() => {
  // 移除窗口大小变化的事件监听器
  window.onresize = null;
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>