vue轮询实现
Vue 轮询实现方法
使用 setInterval 实现基础轮询
在 Vue 组件中通过 setInterval 创建定时任务,适合简单场景:
export default {
data() {
return {
pollInterval: null,
pollData: null
}
},
mounted() {
this.startPolling()
},
beforeDestroy() {
clearInterval(this.pollInterval)
},
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data')
this.pollData = response.data
} catch (error) {
console.error('Polling error:', error)
}
},
startPolling() {
this.pollInterval = setInterval(this.fetchData, 5000) // 每5秒执行一次
}
}
}
使用 setTimeout 实现递归轮询
更可控的轮询方式,可在请求完成后才设置下一次轮询:
methods: {
async pollWithTimeout() {
try {
const response = await axios.get('/api/data')
this.pollData = response.data
} catch (error) {
console.error('Polling error:', error)
} finally {
setTimeout(this.pollWithTimeout, 3000) // 3秒后再次执行
}
}
}
带条件判断的智能轮询
根据业务逻辑动态调整轮询频率或停止轮询:
methods: {
async smartPolling() {
const response = await axios.get('/api/status')
if (response.data.completed) {
clearInterval(this.pollInterval)
return
}
// 根据状态动态调整间隔
const nextDelay = response.data.progress > 50 ? 10000 : 5000
this.pollInterval = setTimeout(this.smartPolling, nextDelay)
}
}
使用 Web Worker 实现后台轮询
避免主线程阻塞的解决方案:
// worker.js
self.addEventListener('message', () => {
setInterval(async () => {
const response = await fetch('/api/data')
postMessage(await response.json())
}, 2000)
})
// Vue组件
created() {
this.worker = new Worker('worker.js')
this.worker.onmessage = (e) => {
this.pollData = e.data
}
},
beforeDestroy() {
this.worker.terminate()
}
轮询最佳实践
- 组件销毁时务必清除定时器
- 错误处理要完善,避免轮询中断
- 考虑添加最大重试次数限制
- 重要操作建议结合 WebSocket 实现实时更新
- 移动端注意心跳包对电池的影响
对于复杂场景,推荐使用专门的状态管理库(如 Vuex)配合轮询机制,实现跨组件状态同步。







