|
|
@@ -1,12 +1,12 @@
|
|
|
<template>
|
|
|
- <div :id="props.id" class="pieChart"></div>
|
|
|
+ <div ref="chartRef" :id="props.id" class="pieChart"></div>
|
|
|
</template>
|
|
|
<script setup lang="ts">
|
|
|
import * as echarts from 'echarts/core';
|
|
|
import { GraphicComponent } from 'echarts/components';
|
|
|
import { PieChart } from 'echarts/charts';
|
|
|
import { CanvasRenderer } from 'echarts/renderers';
|
|
|
- import { onMounted, ref, watch } from 'vue';
|
|
|
+ import { onMounted, onUnmounted, ref, watch } from 'vue';
|
|
|
import type { PieChartData } from '../types';
|
|
|
|
|
|
const props = defineProps<{
|
|
|
@@ -15,31 +15,39 @@
|
|
|
}>();
|
|
|
|
|
|
echarts.use([PieChart, GraphicComponent, CanvasRenderer]);
|
|
|
+ const chartRef = ref<HTMLElement | null>(null);
|
|
|
|
|
|
const sum = ref(props.data.reduce((acc, cur) => acc + cur.value, 0));
|
|
|
- let doughnut;
|
|
|
+ let chartElement;
|
|
|
|
|
|
onMounted(() => {
|
|
|
- doughnut = echarts.init(document.getElementById(props.id as string)!);
|
|
|
- if (doughnut) {
|
|
|
- initDoughnut(doughnut);
|
|
|
- drawDoughnut(doughnut);
|
|
|
+ chartElement = echarts.init(chartRef.value!);
|
|
|
+ if (chartElement) {
|
|
|
+ initChart(chartElement);
|
|
|
+ drawChart(chartElement);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
- const drawDoughnut = (doughnut) => {
|
|
|
- const doughnutOption = {
|
|
|
+ onUnmounted(() => {
|
|
|
+ window.removeEventListener('resize', handleResize);
|
|
|
+ if (chartElement) {
|
|
|
+ chartElement.dispose();
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ const drawChart = (doughnut: echarts.ECharts) => {
|
|
|
+ const chartOption = {
|
|
|
series: [
|
|
|
{
|
|
|
data: props.data,
|
|
|
},
|
|
|
],
|
|
|
};
|
|
|
- doughnut.setOption(doughnutOption);
|
|
|
+ doughnut.setOption(chartOption);
|
|
|
};
|
|
|
|
|
|
- const initDoughnut = (doughnut) => {
|
|
|
- const doughnutOption = {
|
|
|
+ const initChart = (doughnut: echarts.ECharts) => {
|
|
|
+ const chartOption = {
|
|
|
graphic: [
|
|
|
{
|
|
|
type: 'group',
|
|
|
@@ -151,14 +159,21 @@
|
|
|
},
|
|
|
],
|
|
|
};
|
|
|
- doughnut.setOption(doughnutOption);
|
|
|
+ doughnut.setOption(chartOption);
|
|
|
+ window.addEventListener('resize', handleResize);
|
|
|
+ };
|
|
|
+ // 处理窗口大小变化
|
|
|
+ const handleResize = () => {
|
|
|
+ if (chartElement) {
|
|
|
+ chartElement.resize();
|
|
|
+ }
|
|
|
};
|
|
|
|
|
|
watch(
|
|
|
() => props.data,
|
|
|
() => {
|
|
|
sum.value = props.data.reduce((acc, cur) => acc + cur.value, 0);
|
|
|
- drawDoughnut(doughnut);
|
|
|
+ drawChart(chartElement);
|
|
|
},
|
|
|
);
|
|
|
</script>
|