refactor: ♻️ eCharts 调整为按需自动导入瘦身打包体积

This commit is contained in:
ray
2025-02-12 17:19:31 +08:00
parent 6b279a272a
commit f5dbff0d9e
4 changed files with 247 additions and 227 deletions

View File

@@ -0,0 +1,76 @@
<!--
* 基于 ECharts Vue3 图表组件
* 版权所有 © 2021-present 有来开源组织
*
* 开源协议https://opensource.org/licenses/MIT
* 项目地址https://gitee.com/youlaiorg/vue3-element-admin
*
* 在使用时请保留此注释感谢您对开源的支持
-->
<template>
<div ref="chartRef" :style="{ width, height }"></div>
</template>
<script setup lang="ts">
import * as echarts from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart, LineChart, PieChart } from "echarts/charts";
import { GridComponent, TooltipComponent, LegendComponent } from "echarts/components";
import { useResizeObserver } from "@vueuse/core";
// 按需注册组件
echarts.use([
CanvasRenderer,
BarChart,
LineChart,
PieChart,
GridComponent,
TooltipComponent,
LegendComponent,
]);
const props = defineProps<{
options: echarts.EChartsCoreOption;
width?: string;
height?: string;
}>();
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
// 初始化图表
const initChart = () => {
if (chartRef.value) {
chartInstance = echarts.init(chartRef.value);
if (props.options) {
chartInstance.setOption(props.options);
}
}
};
// 监听尺寸变化,自动调整
useResizeObserver(chartRef, () => {
chartInstance?.resize();
});
// 监听 options 变化,更新图表
watch(
() => props.options,
(newOptions) => {
if (chartInstance && newOptions) {
chartInstance.setOption(newOptions);
}
},
{ deep: true }
);
onMounted(() => {
nextTick(() => initChart());
});
onBeforeUnmount(() => {
chartInstance?.dispose();
});
</script>