Files
vue3-element-admin/src/components/ECharts/index.vue

77 lines
1.7 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
* 基于 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>