77 lines
1.7 KiB
Vue
77 lines
1.7 KiB
Vue
<!--
|
||
* 基于 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>
|