程序化的事件偵聽器
比如,在頁面掛載時定義計時器,需要在頁面銷毀時清除定時器。這看起來沒什么問題。但仔細一看 this.timer 唯一的作用只是為了能夠在 beforeDestroy 內取到計時器序號,除此之外沒有任何用處。
export default {
mounted() {
this.timer = setInterval(() => {
console.log(Date.now())
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
如果可以的話最好只有生命周期鈎子可以訪問到它。這並不算嚴重的問題,但是它可以被視為雜物。
我們可以通過 $on 或 $once 監聽頁面生命周期銷毀來解決這個問題:
export default {
mounted() {
this.creatInterval('hello')
this.creatInterval('world')
},
creatInterval(msg) {
let timer = setInterval(() => {
console.log(msg)
}, 1000)
this.$once('hook:beforeDestroy', function() {
clearInterval(timer)
})
}
}
使用這個方法后,即使我們同時創建多個計時器,也不影響效果。因為它們會在頁面銷毀后程序化的自主清除。
