页面中设置了定时器,如果组件销毁是没有关闭定时器,他还会一直执行,会非常耗性能,所以需要及时关闭定时器。 

activated,deactivated生命周期的用法

关闭定时器

vue项目中,正常情况下,我们在生命周期 destroyed 中关闭即可,一旦页面中使用了keep-alive 进行缓存,此时 destroyed 会失效。需要在 deactivated 钩子函数去关闭,他是 keep-alive 特有的钩子函数。

没有缓存页面

destroyed(){
	clearInterval(this.timer)
}

keep-alive 缓存过的页面

// 开启定时器
activated(){
	this.start()
},
// 关闭定时器
deactivated(){
	clearInterval(this.timer)
}

注意:只有当组件在<keep - alive >内被切换,才会有activated和deactivated这两个钩子函数