123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- import type { EChartsOption } from 'echarts';
- import type { Ref } from 'vue';
- import { useTimeoutFn } from '/@/hooks/core/useTimeout';
- import { tryOnUnmounted } from '@vueuse/core';
- import { unref, nextTick, watch, computed, ref } from 'vue';
- import { useDebounce } from '/@/hooks/core/useDebounce';
- import { useEventListener } from '/@/hooks/event/useEventListener';
- import { useBreakpoint } from '/@/hooks/event/useBreakpoint';
- import echarts from './echarts';
- import { useRootSetting } from '/@/hooks/setting/useRootSetting';
- export function useECharts(
- elRef: Ref<HTMLDivElement>,
- theme: 'light' | 'dark' | 'default' = 'light'
- ) {
- const { getDarkMode } = useRootSetting();
- let chartInstance: echarts.ECharts | null = null;
- let resizeFn: Fn = resize;
- const cacheOptions = ref<EChartsOption>({});
- let removeResizeFn: Fn = () => {};
- const [debounceResize] = useDebounce(resize, 200);
- resizeFn = debounceResize;
- const getOptions = computed(
- (): EChartsOption => {
- if (getDarkMode.value !== 'dark') {
- return cacheOptions.value;
- }
- return {
- backgroundColor: 'transparent',
- ...cacheOptions.value,
- };
- }
- );
- 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) {
- useTimeoutFn(() => {
- resizeFn();
- }, 30);
- }
- }
- function setOptions(options: EChartsOption, clear = true) {
- cacheOptions.value = options;
- if (unref(elRef)?.offsetHeight === 0) {
- useTimeoutFn(() => {
- setOptions(unref(getOptions));
- }, 30);
- return;
- }
- nextTick(() => {
- useTimeoutFn(() => {
- if (!chartInstance) {
- initCharts(getDarkMode.value);
- 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);
- setOptions(cacheOptions.value);
- }
- }
- );
- tryOnUnmounted(() => {
- if (!chartInstance) return;
- removeResizeFn();
- chartInstance.dispose();
- chartInstance = null;
- });
- return {
- setOptions,
- resize,
- echarts,
- };
- }
|