VUE 设置定时器和清理定时器


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

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,但是任务依然在继续运行
}复制代码

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

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

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

 

哇,成功了...

 

 

 

 

  

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM