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 } }