vue中清除定时器

版权声明:本文章可转载,转载请注明本文地址,谢谢~ https://blog.csdn.net/weixin_43307658/article/details/89424597

欢迎访问我的博客https://qqqww.com/,祝码农同胞们早日走上人生巅峰,迎娶白富美~~~

1 前言

最近看《vue.js实战》这本书,看到清除定时器在beforeDestroy钩子函数中进行,但是按照经验,我记得destroyed中也是可以的,于是自己建了一个vue-cli工程去研究清除定时器的一些方法

2 方式一

export default {
		data() {
			return {
				timer: null
			}
		},
		created() {
			this.getBanner()
			console.log('created')
		},
		mounted() {
			console.log('mounted')
			this.timer = setInterval(() => {
				console.log('1')
			}, 500);
		},
    	updated() {
			console.log('updated')
		},
		beforeDestroy() {
			console.log('beforeDestroy' + '==========' + this.timer)
			// clearInterval(this.timer)
		},
		destroyed() {
			console.log('destroyed' + '=========' + this.timer)
			clearInterval(this.timer)
		}
}

在页面挂在的时候设置了一个定时器,首先看看钩子函数的场景,createdmounted在页面渲染的时候就都会执行出来,具体看控制台打印,当数据更新,执行updated,然后我做了个路由跳转,将该页面跳转到另外一个页面,此时控制台打印beforeDestroy==========54destroyed=========54,可见当页面跳转完成,这两个钩子函数都会执行,所以我在这两个地方分别尝试去清除定时器,都是可以的

3 方式二

去网上找到一种方法,利用$once监听

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

看了很多文档,都推荐方式二,但始终没搞明白为什么方式二就好

4 缓存

然后尝试使用keep-alive对组件进行缓存,发现并不能销毁,这是destroyed是不执行的,若要清除定时器只能在beforeDestroy

5 参考文档

猜你喜欢

转载自blog.csdn.net/weixin_43307658/article/details/89424597
今日推荐