今日跟朋友交流,偶然间被问到这个问题:“在vue的生命周期中定义一个定时器,如何在destoryed钩子中不手动卸载的操作下,自动卸载定时器“ 引发了一些思考,也总结出一些之前未接触的代码操作,付诸君一哂
// vue中常见的定义定时器销毁操作如下
export default {
...
mounted(){
this.timer = setTimeout(()=>{
//一些操作
},1000)
},
beforeDestroy(){
clearTimeout(this.timer)
}
}
现在介绍一下更加优雅的写法
export default {
...
mounted(){
let timer = setTimeout(()=>{
//一些操作
},1000)
this.$once('hook:beforeDestroy',()=>{
clearTimeout(timer)
timer = null
})
}
}
注意在有keep-alive包裹的组件中不会执行destroy相关的钩子,所以在deactived钩子中清除
export default {
...
mounted(){
let timer = setTimeout(()=>{
//一些操作
},1000)
this.$on('hook:actived',()=>{ //使用$on,需要多次执行
if(timer){
clearTimeout(timer)
}else{
timer = setTimeout(()=>{
//一些操作
},1000)
}
timer = null
})
this.$on('hook:deactived',()=>{ //使用$on,需要多次执行
clearTimeout(timer)
timer = null
})
}
}