vue长轮询代码实现
Vue 长轮询实现方法
长轮询(Long Polling)是一种模拟实时通信的技术,通过客户端持续向服务器发送请求并保持连接,直到服务器有新数据或超时返回。以下是基于 Vue 的实现方式:
基础实现
封装一个长轮询函数,通过递归或循环实现持续请求:
// utils/longPolling.js
export function startLongPolling(url, interval = 30000) {
return new Promise((resolve, reject) => {
const fetchData = async () => {
try {
const response = await fetch(url)
const data = await response.json()
resolve(data)
} catch (error) {
setTimeout(fetchData, interval)
}
}
fetchData()
})
}
在Vue组件中使用
在组件中调用长轮询并处理数据更新:
import { startLongPolling } from '@/utils/longPolling'
export default {
data() {
return {
messages: []
}
},
mounted() {
this.initLongPolling()
},
methods: {
async initLongPolling() {
const data = await startLongPolling('/api/messages')
this.messages = data.messages
this.initLongPolling() // 递归调用实现持续轮询
}
}
}
优化版本(带终止控制)
添加终止机制避免内存泄漏:
export default {
data() {
return {
messages: [],
polling: null
}
},
methods: {
startPolling() {
const poll = async () => {
try {
const res = await axios.get('/api/updates')
this.messages = res.data
} finally {
this.polling = setTimeout(poll, 10000)
}
}
poll()
},
stopPolling() {
clearTimeout(this.polling)
}
},
beforeDestroy() {
this.stopPolling()
}
}
使用Web Worker
对于复杂场景可将轮询逻辑放入Web Worker:
// worker.js
self.addEventListener('message', () => {
const poll = () => {
fetch('/api/data').then(res => {
self.postMessage(res.data)
setTimeout(poll, 5000)
})
}
poll()
})
// Vue组件
const worker = new Worker('./worker.js')
worker.onmessage = (e) => {
this.data = e.data
}
注意事项
- 服务器端需要实现长轮询接口,保持连接直到数据更新或超时
- 适当设置超时时间(通常30-60秒)
- 组件销毁时务必清除轮询定时器
- 考虑添加错误重试机制
- 对于高频更新场景建议改用WebSocket
以上实现可根据具体需求调整轮询间隔、错误处理等逻辑。







