Vue 组件里的定时器要怎么销毁?

如果页面上有很多定时器,可以在 data 选项中创建一个对象 timer,给每个定时器取个名字一一映射在对象 timer 中, 在 beforeDestroy 构造函数中清除,

beforeDestroy(){
	for(let k in this.timer){
		clearInterval(k)
	}
}

如果页面只有单个定时器,可以这么做

const timer = setInterval(() =>{}, 500);
this.$once('hook:beforeDestroy', ()=>{
	clearInterval(timer)
})
posted @ 2023-11-14 19:15  煜火  阅读(130)  评论(0)    收藏  举报