UNPKG

create-iking-admin

Version:

金合技术中台脚手架

116 lines (101 loc) 3.1 kB
import { useBreakpoint } from '@/global/hooks/event/useBreakpoint'; import { useEventListener } from '@/global/hooks/event/useEventListener'; import { useRootSetting } from '@/global/hooks/setting/useRootSetting'; import echarts from '@/mainApp/utils/lib/echarts'; import { tryOnUnmounted, useDebounceFn } from '@vueuse/core'; import type { EChartsOption } from 'echarts'; import { ikingCore } from 'iking-vue-hooks'; import type { Ref } from 'vue'; import { computed, nextTick, ref, unref, watch } from 'vue'; export function useECharts( elRef: Ref<HTMLDivElement>, theme: 'light' | 'dark' | 'default' = 'default', ) { const { getDarkMode: getSysDarkMode } = useRootSetting(); const getDarkMode = computed(() => { return theme === 'default' ? getSysDarkMode.value : theme; }); let chartInstance: echarts.ECharts | null = null; let resizeFn: Fn = resize; const cacheOptions = ref({}) as Ref<EChartsOption>; let removeResizeFn: Fn = () => {}; resizeFn = useDebounceFn(resize, 200); const getOptions = computed(() => { if (getDarkMode.value !== 'dark') { return cacheOptions.value as EChartsOption; } return { backgroundColor: 'transparent', ...cacheOptions.value, } as EChartsOption; }); function initCharts(t = theme) { const el = unref(elRef); if (!el || !unref(el)) { return; } chartInstance = echarts.init(el, t); const { removeEvent } = useEventListener({ el: window, name: 'resize', listener: resizeFn, }); removeResizeFn = removeEvent; const { widthRef, screenEnum } = useBreakpoint(); if (unref(widthRef) <= screenEnum.MD || el.offsetHeight === 0) { ikingCore.useTimeoutFn(() => { resizeFn(); }, 30); } } function setOptions(options: EChartsOption, clear = true) { cacheOptions.value = options; if (unref(elRef)?.offsetHeight === 0) { ikingCore.useTimeoutFn(() => { setOptions(unref(getOptions)); }, 30); return; } nextTick(() => { ikingCore.useTimeoutFn(() => { if (!chartInstance) { initCharts(getDarkMode.value as 'default'); if (!chartInstance) return; } clear && chartInstance?.clear(); chartInstance?.setOption(unref(getOptions)); }, 30); }); } function resize() { chartInstance?.resize(); } watch( () => getDarkMode.value, (theme) => { if (chartInstance) { chartInstance.dispose(); initCharts(theme as 'default'); setOptions(cacheOptions.value); } }, ); tryOnUnmounted(() => { if (!chartInstance) return; removeResizeFn(); chartInstance.dispose(); chartInstance = null; }); function getInstance(): echarts.ECharts | null { if (!chartInstance) { initCharts(getDarkMode.value as 'default'); } return chartInstance; } return { setOptions, resize, echarts, getInstance, }; }