经过验证后,所使用的定时器的方式:
data:{
return{
timer:null
}
},
methods:{
// 开始定时器
timeClock(){
if(this.timer == null){
this.timer = setInterval ( () => {
this.uploadStatus()
},1000)
}
}
// 关闭定时器
this.$once('hook:beforeDestory', () => {
clearInterval(this.timer)
this.timer = null
})
}
总结:
通过$once来监听定时器,在beforeDestory的钩子中,可以清除定时器;
即:关闭页面(切换路由)时,关闭定时器
注意:
在笔者的项目中,尝试使用过destoryed钩子,beforeRouterLeave钩子,beforeDestory()钩子,但都清除不掉定时器;
destoryed:function () {}
beforeRouterLeave (to ,from ,next) {}
beforeDestory () {}
所以,依然建议使用上文代码所示的方法关闭定时器;
(在离开当前页面时,定时器一定要关闭,不然过于消耗后台的资源)
完成!!!