使用setInterval可能会产生 1.刷新页面时轮询时间错误 以及 2.页面销毁定时器未成功销毁 的问题,因此,此处使用setTimeout
// 页面渲染成功后开始轮询接口
created() {
this.setTimer(0)
},
// 页面销毁前销毁定时器
beforeDestroy() {
if (this.timer) {
clearTimeout(this.timer)
}
},
methods: {
// 轮询方法
setTimer(time) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
this.getList()
}, time)
},
// api接口
getList() {
api(query).then(res => {
if (res.success) {
this.setTimer(10000)
}
})
},
}