Export chartRef for use options update chart.

增加chart图表对象引用的导出,方便从服务端获取到数据后更新图表。
This commit is contained in:
RockerHX 2022-10-11 11:16:03 +08:00 committed by GitHub
parent abd02d1990
commit 06783068be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -86,19 +86,19 @@ export function useEcharts(
const initialSize = { width: 0, height: 0 }; const initialSize = { width: 0, height: 0 };
const { width, height } = useElementSize(domRef, initialSize); const { width, height } = useElementSize(domRef, initialSize);
let chart: echarts.ECharts | null = null; const chartRef = ref<echarts.ECharts>();
function canRender() { function canRender() {
return initialSize.width > 0 && initialSize.height > 0; return initialSize.width > 0 && initialSize.height > 0;
} }
function isRendered() { function isRendered() {
return Boolean(domRef.value && chart); return Boolean(domRef.value && chartRef.value);
} }
function update(updateOptions: ECOption) { function update(updateOptions: ECOption) {
if (isRendered()) { if (isRendered()) {
chart!.setOption({ ...updateOptions, backgroundColor: 'transparent' }); chartRef.value!.setOption({ ...updateOptions, backgroundColor: 'transparent' });
} }
} }
@ -106,20 +106,20 @@ export function useEcharts(
if (domRef.value) { if (domRef.value) {
const chartTheme = theme.darkMode ? 'dark' : 'light'; const chartTheme = theme.darkMode ? 'dark' : 'light';
await nextTick(); await nextTick();
chart = echarts.init(domRef.value, chartTheme); chartRef.value = echarts.init(domRef.value, chartTheme);
if (renderFun) { if (renderFun) {
renderFun(chart); renderFun(chartRef.value);
} }
update(options.value); update(options.value);
} }
} }
function resize() { function resize() {
chart?.resize(); chartRef.value?.resize();
} }
function destroy() { function destroy() {
chart?.dispose(); chartRef.value?.dispose();
} }
function updateTheme() { function updateTheme() {
@ -132,7 +132,7 @@ export function useEcharts(
initialSize.height = newHeight; initialSize.height = newHeight;
if (newWidth === 0 && newHeight === 0) { if (newWidth === 0 && newHeight === 0) {
// 节点被删除 将chart置为空 // 节点被删除 将chart置为空
chart = null; chartRef.value = undefined;
} }
if (canRender()) { if (canRender()) {
if (!isRendered()) { if (!isRendered()) {
@ -162,6 +162,7 @@ export function useEcharts(
}); });
return { return {
domRef domRef,
chartRef
}; };
} }