共计 2355 个字符,预计需要花费 6 分钟才能阅读完成。
import { ref, unref, nextTick, onMounted } from "vue";
import empty from "@/assets/image/public/empty.png";
import type { Ref } from "vue";
import echarts from "@/libs/echarts";
import { useResizeObserver } from "@vueuse/core";
export const useECharts = (
elRef: RefHTMLDivElement>,
params?: {
theme?: "light" | "dark" | "default";
loadingText?: string;
}
): any => {
let chartInstancec: echarts.ECharts | null = null;
const cacheOptions = ref({}) as Refany>;
const initCharts = () => {
const el = unref(elRef);
if (!el || !unref(el)) {
return;
}
chartInstancec = echarts.init(elRef.value, params?.theme || "default");
chartInstancec?.showLoading({
text: params?.loadingText || "正在加载数据",
});
};
const setOptions = (options: any) => {
chartInstancec?.clear();
cacheOptions.value = options;
nextTick(() => {
if (!chartInstancec) return;
chartInstancec?.hideLoading();
chartInstancec?.setOption(unref(cacheOptions));
});
};
const setNotopt = () => {
chartInstancec?.clear();
const tempOpt = {
title: {
text: "{a|}",
x: "center",
y: "center",
itemGap: 0,
textStyle: {
rich: {
a: {
color: "#000",
fontSize: "16",
height: elRef.value.offsetHeight / 1.5,
width: elRef.value.offsetWidth / 4,
backgroundColor: {
image: empty,
},
},
},
},
},
};
setOptions(tempOpt);
};
const getInstance = () => {
if (!chartInstancec) {
initCharts();
}
return chartInstancec;
};
useResizeObserver(elRef, () => {
if (chartInstancec) chartInstancec?.resize();
});
onMounted(() => {
initCharts();
});
return [setOptions, setNotopt, getInstance];
};
import * as echarts from "echarts/core";
import {
BarChart,
LineChart,
PieChart,
MapChart,
PictorialBarChart,
RadarChart,
ScatterChart,
SunburstChart,
GaugeChart,
} from "echarts/charts";
import {
TitleComponent,
TooltipComponent,
GridComponent,
PolarComponent,
AriaComponent,
ParallelComponent,
LegendComponent,
RadarComponent,
ToolboxComponent,
DataZoomComponent,
VisualMapComponent,
TimelineComponent,
CalendarComponent,
GraphicComponent,
} from "echarts/components";
import { SVGRenderer } from "echarts/renderers";
echarts.use([
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
PolarComponent,
AriaComponent,
ParallelComponent,
BarChart,
LineChart,
PieChart,
MapChart,
RadarChart,
SVGRenderer,
PictorialBarChart,
RadarComponent,
ToolboxComponent,
DataZoomComponent,
VisualMapComponent,
TimelineComponent,
CalendarComponent,
GraphicComponent,
ScatterChart,
SunburstChart,
GaugeChart,
]);
export default echarts;
使用:
import { useECharts } from "@/compositionAPI/useECharts";
const [setOptions, setNotopt] = useECharts(tempRef);
setOptions(option);
setNotopt();
原文地址: useEcharts 更加方便的使用 echarts,echarts 动态尺寸,
正文完