vue3中实现接口轮询
vue3 中实现接口轮询的方法
使用 setInterval 实现基础轮询
在 Vue3 的 setup 中通过 setInterval 定时调用接口:
import { onMounted, onUnmounted, ref } from 'vue'
import axios from 'axios'
const data = ref(null)
let pollInterval = null
const fetchData = async () => {
try {
const response = await axios.get('/api/data')
data.value = response.data
} catch (error) {
console.error('轮询请求失败:', error)
}
}
onMounted(() => {
pollInterval = setInterval(fetchData, 5000) // 每5秒请求一次
})
onUnmounted(() => {
clearInterval(pollInterval) // 组件卸载时清除定时器
})
使用 setTimeout 实现可调节间隔的轮询
更灵活的递归调用方式,可根据响应结果动态调整间隔:

const pollWithTimeout = async (interval = 5000) => {
await fetchData()
setTimeout(() => pollWithTimeout(interval), interval)
}
onMounted(() => {
pollWithTimeout()
})
带错误处理的增强版轮询
增加错误重试机制和最大重试次数限制:
const MAX_RETRIES = 3
let retryCount = 0
const fetchDataWithRetry = async () => {
try {
const response = await axios.get('/api/data')
data.value = response.data
retryCount = 0 // 成功时重置重试计数
} catch (error) {
if (retryCount < MAX_RETRIES) {
retryCount++
console.log(`第 ${retryCount} 次重试...`)
} else {
console.error('达到最大重试次数')
clearInterval(pollInterval)
}
}
}
使用 Web Worker 实现后台轮询
避免主线程阻塞的解决方案:

// worker.js
self.onmessage = function(e) {
setInterval(() => {
fetch('/api/data')
.then(res => res.json())
.then(data => self.postMessage(data))
}, e.data.interval)
}
// 组件中
const worker = new Worker('./worker.js')
worker.onmessage = (e) => {
data.value = e.data
}
onUnmounted(() => worker.terminate())
基于 Composition API 的复用方案
封装成可复用的 composable 函数:
// usePolling.js
import { ref, onUnmounted } from 'vue'
export function usePolling(fetchFn, interval = 5000) {
const data = ref(null)
let timer = null
const start = () => {
const execute = async () => {
data.value = await fetchFn()
timer = setTimeout(execute, interval)
}
execute()
}
const stop = () => {
clearTimeout(timer)
}
onUnmounted(stop)
return { data, start, stop }
}
// 组件中使用
import { usePolling } from './usePolling'
const { data } = usePolling(async () => {
const res = await axios.get('/api/data')
return res.data
}, 3000)
智能轮询策略(根据网络状态调整)
通过 navigator.onLine 检测网络状态优化轮询:
const adaptivePolling = () => {
if (!navigator.onLine) {
console.log('网络离线,暂停轮询')
return
}
fetchData()
const delay = data.value?.priority ? 2000 : 5000
setTimeout(adaptivePolling, delay)
}
每种方法适用于不同场景,基础项目可使用简单 setInterval 方案,复杂应用建议采用 composable 封装或 Web Worker 方案。注意组件卸载时务必清除定时器,避免内存泄漏。






