useECharts.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { useTimeout } from '/@/hooks/core/useTimeout';
  2. import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
  3. import { ref, 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. const chartInstanceRef = ref<Nullable<ECharts>>(null);
  15. let resizeFn: Fn = resize;
  16. const [debounceResize] = useDebounce(resize, 200);
  17. resizeFn = debounceResize;
  18. function init() {
  19. const el = unref(elRef);
  20. if (!el || !unref(el)) {
  21. return;
  22. }
  23. chartInstanceRef.value = echarts.init(el, theme);
  24. useEvent({
  25. el: window,
  26. name: 'resize',
  27. listener: resizeFn,
  28. });
  29. const { widthRef, screenEnum } = useBreakpoint();
  30. if (unref(widthRef) <= screenEnum.MD) {
  31. useTimeout(() => {
  32. resizeFn();
  33. }, 30);
  34. }
  35. }
  36. function setOptions(options: any, clear = true) {
  37. nextTick(() => {
  38. useTimeout(() => {
  39. let chartInstance = unref(chartInstanceRef);
  40. if (!chartInstance) {
  41. init();
  42. chartInstance = chartInstance = unref(chartInstanceRef);
  43. if (!chartInstance) {
  44. return;
  45. }
  46. }
  47. clear && chartInstance.clear();
  48. chartInstance && chartInstance.setOption(options);
  49. }, 30);
  50. });
  51. }
  52. function resize() {
  53. const chartInstance = unref(chartInstanceRef);
  54. if (!chartInstance) return;
  55. chartInstance.resize();
  56. }
  57. tryOnUnmounted(() => {
  58. const chartInstance = unref(chartInstanceRef);
  59. if (!chartInstance) return;
  60. chartInstance.dispose();
  61. chartInstanceRef.value = null;
  62. });
  63. return {
  64. setOptions,
  65. echarts,
  66. };
  67. }