使用钩子函数对定时器进行清理,失败了,

1、在data中声明要设置的定时器名称:

data() {            
    return {                              
        timer: null  // 定时器名称          
    }        
},复制代码

2、在mounted中创建定时器:

this.timer = (() => {
    // 某些操作
}, 5000)复制代码

3、在页面注销时清理定时器:

beforeDestroy() {
    clearInterval(this.timer);        
    this.timer = null;
}复制代码

然鹅,并没什么卵用,在切换页面后,定时任务依然顽强的奔跑着。

beforeDestroy() {
    clearInterval(this.timer);        
    this.timer = null;
    console.log(this.timer)            //输出为: null,但是任务依然在继续运行
}复制代码

可能是我的姿势不对吧。害羞.jpg

经过在各大论坛一番查找发现:

通过$once这个事件侦听器在定义完定时器之后的位置来清除定时器:

const timer = setInterval(() =>{                    
    // 某些定时器操作                
}, 5000);            
// 通过$once来监听定时器
// 在beforeDestroy钩子触发时清除定时器
this.$once('hook:beforeDestroy', () => {            
    clearInterval(timer);                                    
}) 复制代码

哇,成功了...







转载于:https://juejin.im/post/5cc17b88f265da03705fbbbe

Logo

前往低代码交流专区

更多推荐