vue 是单页面应用,路由切换后,定时器并不会自动关闭,需要手动清除,当页面被销毁时,清除定时器即可。
方案一:
(这样不是最优方案,详细看官方文档 )
data() {
return {
timer: null // 定时器名称
}
},
mounted(){
this.timer = (() => {
// 某些操作
}, 1000)
},
//最后在beforeDestroy()生命周期内清除定时器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
方案二:
(类似于其他需要在当前页面使用,离开需要销毁的组件(例如一些第三方库的picker组件等等),都可以使用此方式来解决离开后以后在背后运行的问题。)
data() {
return {
timer: null // 定时器名称
}
},
mounted(){
this.timer = (() => {
// 某些操作
}, 1000)
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {
clearInterval(this.timer);
},
}