在项目开发中,如果用到定时器,就需要在页面挂载时定义计时器,在页面销毁时清除定时器。下面代码就是常规写法。
export default {
mounted() {
this.timer = setInterval(() => {
console.log('hello world')
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
这看起来没什么问题。但仔细一看 this.timer 唯一的作用只是为了能够在 beforeDestroy 内取到计时器序号,除此之外没有任何用处。还发现自己不得不在单个组件里做很多建立和清理的工作,所以我们可以通过 $on 或 $once 监听页面生命周期销毁来解决这个问题
export default {
mounted() {
this.creatInterval('hello')
this.creatInterval('world')
},
methods:{
creatInterval(msg) {
let timer = setInterval(() => {
console.log(msg)
}, 1000)
this.$once('hook:beforeDestroy', function() {
clearInterval(timer)
})
}
}
}
这样的话,我们即使在页面中创建多个定时器,也会在页面摧毁前程序化摧毁。这样就优雅许多。
参考文档:Vue官方文档地址