2020-11-21 22:47:10 +08:00
|
|
|
|
import { useTimeoutFn } from '/@/hooks/core/useTimeout';
|
2020-10-11 14:53:04 +08:00
|
|
|
|
import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
|
2020-11-04 21:00:17 +08:00
|
|
|
|
import { unref, Ref, nextTick } from 'vue';
|
2020-10-11 14:53:04 +08:00
|
|
|
|
|
|
|
|
|
import ApexCharts from 'apexcharts';
|
|
|
|
|
|
2020-12-23 00:14:51 +08:00
|
|
|
|
interface CallBackFn {
|
|
|
|
|
(instance: Nullable<ApexCharts>): void;
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-11 14:53:04 +08:00
|
|
|
|
export function useApexCharts(elRef: Ref<HTMLDivElement>) {
|
2020-11-04 21:00:17 +08:00
|
|
|
|
let chartInstance: Nullable<ApexCharts> = null;
|
2020-10-11 14:53:04 +08:00
|
|
|
|
|
2020-12-23 00:14:51 +08:00
|
|
|
|
function setOptions(options: any, callback?: CallBackFn) {
|
2020-10-11 22:59:44 +08:00
|
|
|
|
nextTick(() => {
|
2020-11-12 22:40:16 +08:00
|
|
|
|
useTimeoutFn(() => {
|
2020-10-11 22:59:44 +08:00
|
|
|
|
const el = unref(elRef);
|
2020-10-11 14:53:04 +08:00
|
|
|
|
|
2020-11-04 21:00:17 +08:00
|
|
|
|
if (!el || !unref(el)) return;
|
|
|
|
|
chartInstance = new ApexCharts(el, options);
|
2020-10-11 14:53:04 +08:00
|
|
|
|
|
|
|
|
|
chartInstance && chartInstance.render();
|
2020-12-23 00:14:51 +08:00
|
|
|
|
|
2020-12-21 22:06:51 +08:00
|
|
|
|
// setOptions增加callback方法,返回chartInstance,以便于对图表进行再操作,例如调用updateOptions方法更新图表
|
|
|
|
|
callback && callback(chartInstance);
|
2020-10-11 14:53:04 +08:00
|
|
|
|
}, 30);
|
|
|
|
|
});
|
|
|
|
|
}
|
2020-12-23 00:14:51 +08:00
|
|
|
|
|
2020-12-21 22:06:51 +08:00
|
|
|
|
// 新增调用ApexCharts的updateOptions方法更新图表
|
|
|
|
|
function updateOptions(
|
2020-12-23 00:14:51 +08:00
|
|
|
|
chartInstance: Nullable<ApexCharts>,
|
|
|
|
|
options: any,
|
|
|
|
|
redraw = false,
|
|
|
|
|
animate = true,
|
|
|
|
|
updateSyncedCharts = true,
|
|
|
|
|
callback: CallBackFn
|
|
|
|
|
) {
|
2020-12-21 22:06:51 +08:00
|
|
|
|
nextTick(() => {
|
|
|
|
|
useTimeoutFn(() => {
|
2020-12-23 00:14:51 +08:00
|
|
|
|
chartInstance && chartInstance.updateOptions(options, redraw, animate, updateSyncedCharts);
|
2020-12-21 22:06:51 +08:00
|
|
|
|
|
|
|
|
|
callback && callback(chartInstance);
|
|
|
|
|
}, 30);
|
2020-12-23 00:14:51 +08:00
|
|
|
|
});
|
2020-12-21 22:06:51 +08:00
|
|
|
|
}
|
2020-10-11 14:53:04 +08:00
|
|
|
|
|
|
|
|
|
tryOnUnmounted(() => {
|
2020-11-04 21:00:17 +08:00
|
|
|
|
if (!chartInstance) return;
|
2020-12-21 23:38:16 +08:00
|
|
|
|
chartInstance?.destroy?.();
|
2020-11-03 21:36:54 +08:00
|
|
|
|
chartInstance = null;
|
2020-10-11 14:53:04 +08:00
|
|
|
|
});
|
2020-11-04 21:00:17 +08:00
|
|
|
|
|
2020-10-11 14:53:04 +08:00
|
|
|
|
return {
|
|
|
|
|
setOptions,
|
2020-12-21 22:06:51 +08:00
|
|
|
|
updateOptions,
|
2020-10-11 14:53:04 +08:00
|
|
|
|
};
|
|
|
|
|
}
|