正常情况下,在页面挂载时定义计时器,需要在页面销毁时清除定时器。
export default {
mounted() {
this.timer = setInterval(() => {
console.log('这是个定时器')
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
我们可以通过 $on
或 $once
监听页面生命周期销毁beforeDestroy
,这种方法即使我们同时创建多个计时器,也不影响效果。因为它们会在页面销毁后程序化的自主清除。
export default {
mounted() {
this.creatInterval( hello )
this.creatInterval( world )
},
creatInterval(msg) {
let timer = setInterval(() => {
console.log('这是个定时器')
}, 1000)
this.$once( hook:beforeDestroy , function() {
clearInterval(timer)
})
}
}