useApexCharts.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { useTimeoutFn } from '/@/hooks/core/useTimeout';
  2. import { unref, Ref, nextTick } from 'vue';
  3. import { tryOnUnmounted } from '@vueuse/core';
  4. interface CallBackFn {
  5. (instance: Nullable<ApexCharts>): void;
  6. }
  7. export function useApexCharts(elRef: Ref<HTMLDivElement>) {
  8. let chartInstance: Nullable<ApexCharts> = null;
  9. function setOptions(options: any, callback?: CallBackFn) {
  10. nextTick(() => {
  11. useTimeoutFn(async () => {
  12. const el = unref(elRef);
  13. if (!el || !unref(el)) return;
  14. const ApexCharts = await (await import('apexcharts')).default;
  15. chartInstance = new ApexCharts(el, options);
  16. chartInstance && chartInstance.render();
  17. // The callback method is added to setOptions to return the chartInstance to facilitate the re-operation of the chart, such as calling the updateOptions method to update the chart
  18. callback && callback(chartInstance);
  19. }, 30);
  20. });
  21. }
  22. // Call the updateOptions method of ApexCharts to update the chart
  23. function updateOptions(
  24. chartInstance: Nullable<ApexCharts>,
  25. options: any,
  26. redraw = false,
  27. animate = true,
  28. updateSyncedCharts = true,
  29. callback: CallBackFn
  30. ) {
  31. nextTick(() => {
  32. useTimeoutFn(() => {
  33. chartInstance && chartInstance.updateOptions(options, redraw, animate, updateSyncedCharts);
  34. callback && callback(chartInstance);
  35. }, 30);
  36. });
  37. }
  38. tryOnUnmounted(() => {
  39. if (!chartInstance) return;
  40. chartInstance?.destroy?.();
  41. chartInstance = null;
  42. });
  43. return {
  44. setOptions,
  45. updateOptions,
  46. };
  47. }