Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
haizhilin2013 opened this issue Jun 22, 2019 · 8 comments
Open

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

haizhilin2013 opened this issue Jun 22, 2019 · 8 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the vue vue label Jun 22, 2019
@WalkAlone0325
Copy link

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

@xindiyang
Copy link

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

@Wu-wb
Copy link

Wu-wb commented Jul 23, 2019

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

@wush12
Copy link

wush12 commented Nov 5, 2019

可以在beforeDestroy里写清除函数

@wql77
Copy link

wql77 commented Dec 17, 2019

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

@kuguchengsha
Copy link

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

@1103442828
Copy link

这里还要考虑 KeepAlive 缓存的情况 建议在deactivated中执行一次销毁

@hyj443
Copy link

hyj443 commented Oct 27, 2021

我之前是在data里定义个timer接收定时器id,然后在beforeDestroy钩子里清除timer

但这么做不好,因为你没必要在vm实例保存它,你用到的时候只是在beforeDestroy钩子里

我们可以在创建定时器后,就马上调用vm.$once去监听beforeDestroy钩子的执行,钩子执行时,执行清除定时器的回调,但只触发一次,触发后,监听器会被移除

this.$once('hook:beforeDestroy', () => {
    clearInterval(timer);
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

9 participants