一般使用:
export default {
mounted(){
this.timer = setInterval(()=>{
console.log(new Date())
},1000)
},
berforeDestroy(){
clearInterval(this.timer)
}
}
使用$on $once监听页面生命周期销毁解决
export default{
mounted(){
this.createInterval('hello')
this.createInterval('word')
},
createInterval(msg){
let timer = setInterval(()=>{
console.log(msg)
},1000)
this.$once('hook:berforeDestroty',function(){
clearInterval(timer)
})
}
}
使用这个方法即是我们建立多个计时器,也不影响效果,因为在页面销毁后程序化的自主清除
文档:https://cn.vuejs.org/v2/guide/components-edge-cases.html#程序化的事件侦听器