Vben
2021-02-25 8a9ca498d70a0a4f66c073fe869fc6d8a3e79a55
src/hooks/web/useApexCharts.ts
@@ -1,37 +1,57 @@
import { useTimeout } from '/@/hooks/core/useTimeout';
import { useTimeoutFn } from '/@/hooks/core/useTimeout';
import { tryOnUnmounted } from '/@/utils/helper/vueHelper';
import { ref, unref, Ref, nextTick } from 'vue';
import { unref, Ref, nextTick } from 'vue';
import ApexCharts from 'apexcharts';
interface CallBackFn {
  (instance: Nullable<ApexCharts>): void;
}
export function useApexCharts(elRef: Ref<HTMLDivElement>) {
  const chartInstanceRef = ref<Nullable<ApexCharts>>(null);
  let chartInstance: Nullable<ApexCharts> = null;
  function setOptions(options: any) {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }
    chartInstanceRef.value = new ApexCharts(el, options);
    const chartInstance = unref(chartInstanceRef);
  function setOptions(options: any, callback?: CallBackFn) {
    nextTick(() => {
      useTimeout(() => {
      useTimeoutFn(async () => {
        const el = unref(elRef);
        if (!el || !unref(el)) return;
        const ApexCharts = await (await import('apexcharts')).default;
        chartInstance = new ApexCharts(el, options);
        chartInstance && chartInstance.render();
        // 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
        callback && callback(chartInstance);
      }, 30);
    });
  }
  // Call the updateOptions method of ApexCharts to update the chart
  function updateOptions(
    chartInstance: Nullable<ApexCharts>,
    options: any,
    redraw = false,
    animate = true,
    updateSyncedCharts = true,
    callback: CallBackFn
  ) {
    nextTick(() => {
      useTimeoutFn(() => {
        chartInstance && chartInstance.updateOptions(options, redraw, animate, updateSyncedCharts);
        callback && callback(chartInstance);
      }, 30);
    });
  }
  tryOnUnmounted(() => {
    const chartInstance = unref(chartInstanceRef);
    if (!chartInstance) {
      return;
    }
    chartInstanceRef.value = null;
    if (!chartInstance) return;
    chartInstance?.destroy?.();
    chartInstance = null;
  });
  return {
    setOptions,
    updateOptions,
  };
}