useECharts.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }, 0);
  34. }
  35. }
  36. function setOptions(options: any, clear = true) {
  37. // function setOptions(options: EChartOption, clear = true) {
  38. let chartInstance = unref(chartInstanceRef);
  39. if (!chartInstance) {
  40. init();
  41. chartInstance = chartInstance = unref(chartInstanceRef);
  42. if (!chartInstance) {
  43. return;
  44. }
  45. }
  46. clear && chartInstance.clear();
  47. nextTick(() => {
  48. useTimeout(() => {
  49. chartInstance && chartInstance.setOption(options);
  50. }, 30);
  51. });
  52. }
  53. function resize() {
  54. const chartInstance = unref(chartInstanceRef);
  55. if (!chartInstance) {
  56. return;
  57. }
  58. chartInstance.resize();
  59. }
  60. tryOnUnmounted(() => {
  61. const chartInstance = unref(chartInstanceRef);
  62. if (!chartInstance) {
  63. return;
  64. }
  65. chartInstance.dispose();
  66. chartInstanceRef.value = null;
  67. });
  68. return {
  69. setOptions,
  70. echarts,
  71. };
  72. }