一、使用this.$once()执行销毁定时器
1.常用写法
data(){
return:{ timer:null}
},
methods:{
startTimer(){
this.timer = setInterval(()=>{ console.log("开启定时器")},1000)
}
},
beforeDestory(){
clearInterval(this.timer)
}
2.使用this.$once执行销毁定时器
methods:{
startTimer(){
this.timer = setInterval(()=>{ console.log("开启定时器")},1000);
this.$once('hook:beforeDestory',()=>{
clearInterval(this.timer)
})
}
},
这样的好处是将开启定时器和销毁定时器放在一起了,也不用全局定义实例,也不用担心逻辑太乱,最后销毁页面忘了清除定时器。