useECharts.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { useTimeout } 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 { useEvent } from '/@/hooks/event/useEvent';
  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 } = useEvent({
  26. el: window,
  27. name: 'resize',
  28. listener: resizeFn,
  29. });
  30. removeResizeFn = removeEvent;
  31. const { widthRef, screenEnum } = useBreakpoint();
  32. if (unref(widthRef) <= screenEnum.MD) {
  33. useTimeout(() => {
  34. resizeFn();
  35. }, 30);
  36. }
  37. }
  38. function setOptions(options: any, clear = true) {
  39. nextTick(() => {
  40. useTimeout(() => {
  41. if (!chartInstance) {
  42. init();
  43. if (!chartInstance) return;
  44. }
  45. clear && chartInstance.clear();
  46. chartInstance && chartInstance.setOption(options);
  47. }, 30);
  48. });
  49. }
  50. function resize() {
  51. if (!chartInstance) return;
  52. chartInstance.resize();
  53. }
  54. tryOnUnmounted(() => {
  55. if (!chartInstance) return;
  56. removeResizeFn();
  57. chartInstance.dispose();
  58. chartInstance = null;
  59. });
  60. return {
  61. setOptions,
  62. echarts,
  63. resize,
  64. };
  65. }