【Vue】清除定时器后定时器仍在运行

当在 Vue 中的 destroyed() 或者 beforeDestroy() 方法里清除定时器后,定时器仍在运行 —— 要看解决方案可以直接滑到最后的代码区~

我们在 vue 中使用 setTimeout() 或 setInterval() 后,通常都会在 destroyed()或 beforeDestroy() 方法里去清除。

data() {
	return {
		timer: null
	}
},
methods: {
	// 开启定时器
	openTimer(){
		var timer = setInterval( () => {
			console.log('定时器运行中');
		}, 1000)
	}
},
mounted() {
	this.openTimer();
},
destroyed(){
	// 判断定时器是否存在,防止某些情况导致控制台报错
	if(this.timer){
	 	clearInterval(this.timer);
		this.timer = null;
	}
}

结果发现关闭或切换页面后,控制台还在每秒打印 “定时器运行中”~,可以尝试把关闭定时器放在beforeRouteLeave()方法中

// 将 destroyed() 改为 beforeRouteLeave()
beforeRouteLeave (to, from, next) {
	if(this.timer){
	 	clearInterval(this.timer);
		this.timer = null;
	}
	next()
}

若只是切换页面,想要切换回来后该页面定时器继续运行,使用beforeRouteEnter()

beforeRouteEnter (to, from, next) {
    next(vm => {
        vm.openTimer();
    })
},

所以当在 Vue 中的 destroyed() 或者 beforeDestroy() 方法里清除定时器后,定时器仍在运行。可以在 beforeRouteLeave() 方法里关闭,beforeRouteEnter() 方法里打开:

data() {
	return {
		timer: null
	}
},
methods: {
	// 开启定时器
	openTimer(){
		var timer = setInterval( () => {
			console.log('定时器运行中');
		}, 1000)
	}
},
mounted() {
	this.openTimer();
},
// 离开或切换页面后关闭定时器
beforeRouteLeave (to, from, next) {
	// 判断定时器是否存在,防止某些情况导致控制台报错
	if(this.timer){
	 	clearInterval(this.timer);
		this.timer = null;
	}
	// next必须得加
	next()
}
// 进入该页面后重新开启定时器
beforeRouteEnter (to, from, next) {
    // 通过 `vm` 访问组件实例,vm相当于this
    next(vm => {
        vm.openTimer();
    })
},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值