useECharts.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { useTimeoutFn } from '/@/hooks/core/useTimeout';
  2. import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
  3. import { unref, Ref, nextTick } from 'vue';
  4. import type { EChartOption, ECharts } from 'echarts';
  5. import echarts from 'echarts';
  6. import { useDebounce } from '/@/hooks/core/useDebounce';
  7. import { useEventListener } from '/@/hooks/event/useEventListener';
  8. import { useBreakpoint } from '/@/hooks/event/useBreakpoint';
  9. export type { EChartOption, ECharts };
  10. export function useECharts(
  11. elRef: Ref<HTMLDivElement>,
  12. theme: 'light' | 'dark' | 'default' = 'light'
  13. ) {
  14. let chartInstance: Nullable<ECharts> = null;
  15. let resizeFn: Fn = resize;
  16. let removeResizeFn: Fn = () => {};
  17. const [debounceResize] = useDebounce(resize, 200);
  18. resizeFn = debounceResize;
  19. function init() {
  20. const el = unref(elRef);
  21. if (!el || !unref(el)) {
  22. return;
  23. }
  24. chartInstance = echarts.init(el, theme);
  25. const { removeEvent } = useEventListener({
  26. el: window,
  27. name: 'resize',
  28. listener: resizeFn,
  29. });
  30. removeResizeFn = removeEvent;
  31. const { widthRef, screenEnum } = useBreakpoint();
  32. if (unref(widthRef) <= screenEnum.MD || el.offsetHeight === 0) {
  33. useTimeoutFn(() => {
  34. resizeFn();
  35. }, 30);
  36. }
  37. }
  38. function setOptions(options: any, clear = true) {
  39. if (unref(elRef)?.offsetHeight === 0) {
  40. useTimeoutFn(() => {
  41. setOptions(options);
  42. }, 30);
  43. return;
  44. }
  45. nextTick(() => {
  46. useTimeoutFn(() => {
  47. if (!chartInstance) {
  48. init();
  49. if (!chartInstance) return;
  50. }
  51. clear && chartInstance?.clear();
  52. chartInstance?.setOption(options);
  53. }, 30);
  54. });
  55. }
  56. function resize() {
  57. chartInstance?.resize();
  58. }
  59. tryOnUnmounted(() => {
  60. if (!chartInstance) return;
  61. removeResizeFn();
  62. chartInstance.dispose();
  63. chartInstance = null;
  64. });
  65. return {
  66. setOptions,
  67. echarts,
  68. resize,
  69. };
  70. }