问题
最近项目中遇到了一个问题,在监控界面有两个定时器,一个定时器每个5秒向后端发送一次请求,另一个定时器用于修改界面的时间(因为存在多个对象而且时间都不一样)。虽然在beforeDestroy钩子中写了销毁定时器方法,但是有时就是不生效。
期望
在监控界面时定时器正常调用,切换其他界面时定时器停止调用。
解决思路
常规的解决方法是在beforeDestroy()钩子与destroyed()钩子中使用
beforeDestroy() {
// 清除多次执行定时器 请求定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
},
destroyed() {
// 清除多次执行定时器 请求定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
},
但是有时未触发该方法,只能想其他解决方法了。
只有在监控界面定时器才执行,其他界面不执行,那是不是只要判断当前的界面name就可以了,如果当前界面name是监控界面的name,那么就继续执行,如果不是清除定时器。
代码
export default {
name: 'statusMonitor',
data() {
return {
dateTimer: null, // 时间计时器
requestTimer: null // 请求计时器
}
},
created() {
this.init()
},
beforeDestroy() {
// 清除定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
},
destroyed() {
// 清除定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
},
methods: {
init() {
// 解决在其他界面时依旧调用bug
if (urlName !== 'statusMonitor') {
// 关闭定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
return
}
api.pageList(data).then((res) => {
...
this.startRequestTimer() // 开启定时器
})
},
// 开启定时器
startRequestTimer() {
// 关闭定时器
clearInterval(this.requestTimer)
clearInterval(this.dateTimer)
// 请求定时器
this.requestTimer = setInterval(() => {
// 需要定时执行的代码
this.init()
}, 2000)
// 时间定时器
this.dateTimer = setInterval(() => {
...
}, 1000)
},
}
}