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

vue

原文链接:https://juejin.im/post/5cc17b88f265da03705fbbbe

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

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);

})

哇,成功了...

以上是 VUE 设置定时器和清理定时器 的全部内容, 来源链接: utcz.com/z/376132.html

回到顶部