1. 新建 echartsLib.js 文件,统一导入需要的组件
import * as echarts from "echarts/core";
import { SVGRenderer, CanvasRenderer } from "echarts/renderers";
import { BarChart, LineChart, PieChart } from "echarts/charts";
import {
TitleComponent,
TooltipComponent,
GridComponent,
LegendComponent,
ToolboxComponent,
DataZoomComponent,
TimelineComponent,
} from "echarts/components";
echarts.use([
BarChart,
LineChart,
PieChart,
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent,
ToolboxComponent,
DataZoomComponent,
TimelineComponent,
CanvasRenderer
]);
export default echarts;
2. 新建 newChart.js 文件封装用法
import { nextTick, onMounted, onUnmounted, unref } from "vue";
import echarts from "./echartsLib.js";
import { SVGRenderer, CanvasRenderer } from "echarts/renderers";
export default function useChart(
elRef,
autoChartSize = false,
animation = false,
theme = "default"
) {
// 设置渲染模式
echarts.use(CanvasRenderer);
// echart实例
let chartInstance = null;
// 初始化图表
const initCharts = () => {
const el = unref(elRef);
if (!el || !unref(el)) {
return;
}
chartInstance = echarts.init(el, theme);
};
const setOption = (option) => {
nextTick(() => {
if (!chartInstance) {
initCharts();
if (!chartInstance) return;
}
chartInstance.setOption(option);
hideLoading();
});
};
// 获取echart实例
function getInstance() {
if (!chartInstance) {
initCharts();
}
return chartInstance;
}
function resize() {
chartInstance?.resize();
}
// 监听元素大小
function watchEl() {
// 添加过渡
if (animation) {
elRef.value.style.transition = "width 1s, height 1s";
}
const resizeObserver = new ResizeObserver((entries) => resize());
resizeObserver.observe(elRef.value);
}
// 显示加载
function showLoading() {
if (!chartInstance) {
initCharts();
}
chartInstance?.showLoading();
}
// 隐藏加载
function hideLoading() {
if (!chartInstance) {
initCharts();
}
chartInstance?.hideLoading();
}
onMounted(() => {
window.addEventListener("resize", resize);
if (autoChartSize) watchEl();
});
onUnmounted(() => {
window.removeEventListener("resize", resize);
});
return {
setOption,
getInstance,
showLoading,
hideLoading,
};
}
3. 使用
<div ref="myChart"></div>
import useChart from "@/utils/useChart";
import { reactive, onMounted, ref } from "vue";
const myChart = ref(null);
const { setOption } = useChart(myChart, true, true);
let option = {}
onMounted(() => {
setOption(option);
});
标签:function,封装,Vue3,import,chartInstance,echarts,resize,const
From: https://www.cnblogs.com/lpkshuai/p/17149011.html