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