-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[vue] vue组件里的定时器要怎么销毁? #446
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
Comments
在生命周期的beforeDestroy或者destroyed进行手动销毁吗? |
当生命周期销毁后,并没有将组件中的计时器销毁,虽然页面上看不出来,但是如果在控制台打印的话,会发现计时器还在运行,所以要销毁计时器,避免代码一直执行 |
const timer = setInterval(() =>{ |
可以在beforeDestroy里写清除函数 |
可以在路由离开前清除 |
那如果我要切出浏览器定时器暂停,切会时定时器还要继续,刚进入页面定时器是不启动的,定时器启动后切出页面后关闭网页后再打开这个网页定时器时启动的 |
这里还要考虑 KeepAlive 缓存的情况 建议在deactivated中执行一次销毁 |
我之前是在data里定义个timer接收定时器id,然后在beforeDestroy钩子里清除timer 但这么做不好,因为你没必要在vm实例保存它,你用到的时候只是在beforeDestroy钩子里 我们可以在创建定时器后,就马上调用vm.$once去监听beforeDestroy钩子的执行,钩子执行时,执行清除定时器的回调,但只触发一次,触发后,监听器会被移除 this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
}) |
[vue] vue组件里的定时器要怎么销毁?
The text was updated successfully, but these errors were encountered: