vue长轮询代码实现
Vue 长轮询实现方法
长轮询(Long Polling)是一种服务器推送技术,客户端发送请求后,服务器保持连接开放直到有新数据或超时。以下是 Vue 中实现长轮询的代码示例。
基本实现逻辑
定义一个方法用于发起请求,递归调用自身以实现持续轮询:

methods: {
startLongPolling() {
axios.get('/api/long-polling-endpoint')
.then(response => {
// 处理返回数据
console.log('Received data:', response.data);
// 无论是否有新数据,立即发起下一次请求
this.startLongPolling();
})
.catch(error => {
console.error('Polling error:', error);
// 错误时延迟重试
setTimeout(() => {
this.startLongPolling();
}, 5000);
});
}
}
生命周期控制
在组件挂载时启动轮询,销毁时清除:

mounted() {
this.startLongPolling();
},
beforeDestroy() {
// 可通过标志位或取消令牌终止轮询
this.isPollingActive = false;
// 若使用axios取消令牌
if (this.cancelToken) {
this.cancelToken.cancel('Component unmounted');
}
}
带取消令牌的改进版
使用 axios 的 CancelToken 实现精确控制:
data() {
return {
cancelToken: null
};
},
methods: {
startLongPolling() {
const source = axios.CancelToken.source();
this.cancelToken = source;
axios.get('/api/endpoint', {
cancelToken: source.token
}).then(response => {
// 处理数据...
this.startLongPolling();
}).catch(thrown => {
if (!axios.isCancel(thrown)) {
console.error('Error:', thrown);
setTimeout(() => this.startLongPolling(), 3000);
}
});
}
}
服务端配合要求
服务端需要实现长轮询逻辑(以 Node.js 为例):
app.get('/api/long-polling-endpoint', (req, res) => {
const checkData = () => {
if (hasNewData()) {
res.json({ data: getNewData() });
} else {
setTimeout(checkData, 1000); // 每秒检查一次
}
};
checkData();
});
注意事项
- 设置合理的超时时间(客户端和服务端)
- 错误处理必须包含网络异常和主动取消的区分
- 高并发场景需考虑服务端性能,可改用 WebSocket
- 移动端注意心跳机制和后台运行限制
实际部署时应根据业务需求调整轮询间隔和错误重试策略。对于频繁更新的场景,建议优先考虑 WebSocket 方案。






