Fe-interview: [vue] vue组件里的定时器要怎么销毁?

Created on 22 Jun 2019  ·  6Comments  ·  Source: haizlin/fe-interview

[vue] vue组件里的定时器要怎么销毁?

vue

Most helpful comment

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

All 6 comments

在生命周期的beforeDestroy或者destroyed进行手动销毁吗?

当生命周期销毁后,并没有将组件中的计时器销毁,虽然页面上看不出来,但是如果在控制台打印的话,会发现计时器还在运行,所以要销毁计时器,避免代码一直执行

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

可以在beforeDestroy里写清除函数

可以在路由离开前清除
beforeRouteLeave(to, from, next) {
//做清除操作。。。
next();
}

那如果我要切出浏览器定时器暂停,切会时定时器还要继续,刚进入页面定时器是不启动的,定时器启动后切出页面后关闭网页后再打开这个网页定时器时启动的

Was this page helpful?
0 / 5 - 0 ratings