- 要解决的问题,当数据查询较慢导致数据返回过慢,需要多次查询才能取到数据
- 思路:使用定时器
setInterval做轮询处理,数据返回成功清除定时器
data() {
return {
timer: null,
timeCount: 0,
}
}
beforeDestory() {
this.setTimerNull();
}
created() {
this.handlePolling();
}
methods: {
handleStopPolling() {
this.timeCount++;
if(this.timeCount > 4) {
this.setTimerNull();
return true;
} else {
return false;
}
}
}
setTimerNull() {
clearInterval(this.timer);
this.timer = null;
}
handlePolling() {
this.handleQuery();
this.timer = setInterval(() => {
let flag = this.handleStopPolling();
if(!flag) {
this.handleQuery();
}
})
}
handleQuery() {
axios.get('xxx').then(res => {
if(res.data.leng>0) {
this.setTimerNull();
}
})
}