解决问题:
1. 使用setInterval,网络慢的情况下,前一条请求未返回结果,后一条请求定时发送了;
2. 请求报错,停止轮询请求;
3. 轮询获取表格数据,若新建数据,调用几次刷新表格,创建几个timer;
4. 网速慢的情况下,轮询结果未返回时,切换路由,timer清除不掉。
实现方案:
export default{
... // 其他定义
data() {
timer: null,
isCurrentRoute: true, // 解决:当轮询未返回结果时,切换路由后,timer清除不掉问题
},
created() {
this.getTableData();
}
methods: {
getTableData() {
this.$http.GetTableData().then(res => { // 发送后台请求
if (res) {
if (this.isCurrentRoute) {
this.timer = setTimeout(async () => {
await (this.timer && clearTimeout(this.timer));
await this.getTableData();
}, 5000)
}
... // 其他操作
} else {
clearTimerout(this.timer);
}
})
}
},
beforeDestroy() {
this.isCurrentRoute= false;
clearTimerout(this.timer);
this.timer = null;
}
}