需求:每隔一段时间获取最新数据,然后渲染到页面。如下图效果。
思路:使用定时器,每隔一段时间发起一次请求。
代码:
data() {
return {
// 定时器
timer: null,
// 展示的数据
info: []
}
},
methods: {
getInfo() {
// 轮询获取更新过程中的信息
let num = 1
if (this.timer) {
clearInterval(this.timer)
} else {
this.timer = setInterval(() => {
// 在这里发送请求获取数据
this.updateInfo.push('升级的第'+ num++ +'步')
if (num === 3) {
clearInterval(this.timer)
this.timer = null
}
}, 1500);
}
}
}
清理定时器的时机:
通常情况下,我们可以在 destroyed钩子函数中清除定时器
但有些时候,比如在