当在 Vue2 中的 destroyed() 或者 beforeDestroy() 方法里清除定时器后,定时器仍在运行 —— 要看解决方案可以直接滑到最后的代码区~
我们在 Vue2 中使用 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() 方法里打开:
<script>
export default {
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();
})
}
}
</script>