vue实现接口轮询
Vue 实现接口轮询的方法
使用 setInterval 实现基础轮询
在 Vue 组件的 mounted 生命周期钩子中设置定时器,定期调用接口:
mounted() {
this.pollInterval = setInterval(() => {
this.fetchData()
}, 5000) // 每5秒轮询一次
},
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data')
this.data = response.data
} catch (error) {
console.error('轮询出错:', error)
}
}
},
beforeDestroy() {
clearInterval(this.pollInterval) // 组件销毁时清除定时器
}
使用递归 setTimeout 实现可控轮询
递归方式可以确保前一次请求完成后再发起下一次请求:
methods: {
startPolling() {
const poll = async () => {
try {
await this.fetchData()
} finally {
this.pollTimer = setTimeout(poll, 3000) // 3秒后再次轮询
}
}
poll()
},
stopPolling() {
clearTimeout(this.pollTimer)
}
}
带错误处理和退避策略的轮询
增加错误处理和指数退避机制:
data() {
return {
retryCount: 0,
maxRetries: 5,
baseDelay: 1000
}
},
methods: {
async pollWithBackoff() {
try {
const response = await axios.get('/api/data')
this.data = response.data
this.retryCount = 0 // 成功时重置重试计数
setTimeout(this.pollWithBackoff, 5000) // 正常间隔
} catch (error) {
if (this.retryCount < this.maxRetries) {
const delay = Math.min(
this.baseDelay * Math.pow(2, this.retryCount),
30000
)
this.retryCount++
setTimeout(this.pollWithBackoff, delay)
}
}
}
}
使用 Web Worker 实现后台轮询
将轮询逻辑移至 Web Worker 避免阻塞主线程:
// worker.js
let intervalId = null
self.onmessage = function(e) {
if (e.data === 'start') {
intervalId = setInterval(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => {
self.postMessage(data)
})
}, 5000)
} else if (e.data === 'stop') {
clearInterval(intervalId)
}
}
// Vue 组件
mounted() {
this.worker = new Worker('worker.js')
this.worker.onmessage = (e) => {
this.data = e.data
}
this.worker.postMessage('start')
},
beforeDestroy() {
this.worker.postMessage('stop')
this.worker.terminate()
}
使用第三方库实现高级轮询
安装并使用 axios-retry 等库增强轮询功能:
import axiosRetry from 'axios-retry'
axiosRetry(axios, {
retries: 3,
retryDelay: (retryCount) => {
return retryCount * 1000
}
})
// 在组件中使用
methods: {
startPolling() {
this.pollInterval = setInterval(() => {
axios.get('/api/data')
.then(response => {
this.data = response.data
})
.catch(error => {
console.error('请求失败:', error)
})
}, 4000)
}
}
每种方法适用于不同场景,基础轮询适合简单需求,递归方式适合需要严格顺序的场景,退避策略适合不稳定的网络环境,Web Worker 适合需要后台持续轮询的情况,第三方库则提供了更完善的错误处理机制。







