gongchunyi
6 天以前 f0c8e8aaf9f41a7ab0f02a23cd7c5de1bffb9e71
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { onMounted, onBeforeUnmount } from 'vue'
 
/**
 * 数据轮询 composable
 * @param {Function} fetchFn - 数据获取函数
 * @param {Object} options - 配置选项
 * @param {number} options.interval - 轮询间隔(毫秒),默认 60000(60秒)
 * @param {boolean} options.immediate - 是否立即执行一次,默认 true
 * @returns {Object} { start, stop, isPolling }
 */
export function usePolling(fetchFn, options = {}) {
  const {
    interval = 60000,
    immediate = true
  } = options
 
  let pollingTimer = null
  const isPolling = { value: false }
 
  const start = () => {
    if (pollingTimer) return
    
    if (immediate) {
      fetchFn()
    }
    
    pollingTimer = setInterval(() => {
      fetchFn()
    }, interval)
    
    isPolling.value = true
  }
 
  const stop = () => {
    if (pollingTimer) {
      clearInterval(pollingTimer)
      pollingTimer = null
    }
    isPolling.value = false
  }
 
  // 组件挂载时自动启动
  onMounted(() => {
    start()
  })
 
  // 组件卸载时自动停止
  onBeforeUnmount(() => {
    stop()
  })
 
  return {
    start,
    stop,
    isPolling
  }
}
 
/**
 * 多函数轮询 composable
 * @param {Function[]} fetchFns - 数据获取函数数组
 * @param {Object} options - 配置选项
 * @param {number} options.interval - 轮询间隔(毫秒),默认 60000(60秒)
 * @param {boolean} options.immediate - 是否立即执行一次,默认 true
 * @returns {Object} { start, stop, isPolling }
 */
export function usePollingMultiple(fetchFns, options = {}) {
  const {
    interval = 60000,
    immediate = true
  } = options
 
  let pollingTimer = null
  const isPolling = { value: false }
 
  const fetchAll = () => {
    fetchFns.forEach(fn => {
      if (typeof fn === 'function') {
        fn()
      }
    })
  }
 
  const start = () => {
    if (pollingTimer) return
    
    if (immediate) {
      fetchAll()
    }
    
    pollingTimer = setInterval(() => {
      fetchAll()
    }, interval)
    
    isPolling.value = true
  }
 
  const stop = () => {
    if (pollingTimer) {
      clearInterval(pollingTimer)
      pollingTimer = null
    }
    isPolling.value = false
  }
 
  // 组件挂载时自动启动
  onMounted(() => {
    start()
  })
 
  // 组件卸载时自动停止
  onBeforeUnmount(() => {
    stop()
  })
 
  return {
    start,
    stop,
    isPolling
  }
}