use-echarts.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import type { EChartsOption } from 'echarts';
  2. import type EchartsUI from './echarts-ui.vue';
  3. import type { Ref } from 'vue';
  4. import { computed, nextTick, watch } from 'vue';
  5. import { usePreferences } from '@vben/preferences';
  6. import {
  7. tryOnUnmounted,
  8. useDebounceFn,
  9. useResizeObserver,
  10. useTimeoutFn,
  11. useWindowSize,
  12. } from '@vueuse/core';
  13. import echarts from './echarts';
  14. type EchartsUIType = typeof EchartsUI | undefined;
  15. type EchartsThemeType = 'dark' | 'light' | null;
  16. function useEcharts(chartRef: Ref<EchartsUIType>) {
  17. let chartInstance: echarts.ECharts | null = null;
  18. let cacheOptions: EChartsOption = {};
  19. const { isDark } = usePreferences();
  20. const { height, width } = useWindowSize();
  21. const resizeHandler: () => void = useDebounceFn(resize, 200);
  22. const getOptions = computed((): EChartsOption => {
  23. if (!isDark.value) {
  24. return {};
  25. }
  26. return {
  27. backgroundColor: 'transparent',
  28. };
  29. });
  30. const initCharts = (t?: EchartsThemeType) => {
  31. const el = chartRef?.value?.$el;
  32. if (!el) {
  33. return;
  34. }
  35. chartInstance = echarts.init(el, t || isDark.value ? 'dark' : null);
  36. return chartInstance;
  37. };
  38. const renderEcharts = (options: EChartsOption, clear = true) => {
  39. cacheOptions = options;
  40. const currentOptions = {
  41. ...options,
  42. ...getOptions.value,
  43. };
  44. return new Promise((resolve) => {
  45. if (chartRef.value?.offsetHeight === 0) {
  46. useTimeoutFn(() => {
  47. renderEcharts(currentOptions);
  48. resolve(null);
  49. }, 30);
  50. return;
  51. }
  52. nextTick(() => {
  53. useTimeoutFn(() => {
  54. if (!chartInstance) {
  55. const instance = initCharts();
  56. if (!instance) return;
  57. }
  58. clear && chartInstance?.clear();
  59. chartInstance?.setOption(currentOptions);
  60. resolve(null);
  61. }, 30);
  62. });
  63. });
  64. };
  65. function resize() {
  66. chartInstance?.resize({
  67. animation: {
  68. duration: 300,
  69. easing: 'quadraticIn',
  70. },
  71. });
  72. }
  73. watch([width, height], () => {
  74. resizeHandler?.();
  75. });
  76. useResizeObserver(chartRef as never, resizeHandler);
  77. watch(isDark, () => {
  78. if (chartInstance) {
  79. chartInstance.dispose();
  80. initCharts();
  81. renderEcharts(cacheOptions);
  82. resize();
  83. }
  84. });
  85. tryOnUnmounted(() => {
  86. // 销毁实例,释放资源
  87. chartInstance?.dispose();
  88. });
  89. return {
  90. renderEcharts,
  91. resize,
  92. };
  93. }
  94. export { useEcharts };
  95. export type { EchartsUIType };