useApexCharts.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { useTimeoutFn } from '/@/hooks/core/useTimeout';
  2. import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
  3. import { unref, Ref, nextTick } from 'vue';
  4. import ApexCharts from 'apexcharts';
  5. export function useApexCharts(elRef: Ref<HTMLDivElement>) {
  6. let chartInstance: Nullable<ApexCharts> = null;
  7. function setOptions(options: any, callback) {
  8. nextTick(() => {
  9. useTimeoutFn(() => {
  10. const el = unref(elRef);
  11. if (!el || !unref(el)) return;
  12. chartInstance = new ApexCharts(el, options);
  13. chartInstance && chartInstance.render();
  14. // setOptions增加callback方法,返回chartInstance,以便于对图表进行再操作,例如调用updateOptions方法更新图表
  15. callback && callback(chartInstance);
  16. }, 30);
  17. });
  18. }
  19. // 新增调用ApexCharts的updateOptions方法更新图表
  20. function updateOptions(
  21. chartInstance: Nullable<ApexCharts>,
  22. options,
  23. redraw = false,
  24. animate = true,
  25. updateSyncedCharts = true,
  26. overwriteInitialConfig = true,
  27. callback) {
  28. nextTick(() => {
  29. useTimeoutFn(() => {
  30. chartInstance && chartInstance.updateOptions(
  31. options,
  32. redraw,
  33. animate,
  34. updateSyncedCharts,
  35. overwriteInitialConfig);
  36. callback && callback(chartInstance);
  37. }, 30);
  38. });
  39. }
  40. tryOnUnmounted(() => {
  41. if (!chartInstance) return;
  42. chartInstance?.destroy?.();
  43. chartInstance = null;
  44. });
  45. return {
  46. setOptions,
  47. updateOptions,
  48. };
  49. }