方案1:
data() {
return {
timer: null // 定时器名称
}
},
然后这样使用定时器:
this.timer = setIterval (() => {
// 某些操作
}, 1000)
最后在beforeDestroy()生命周期内清除定时器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
次方案有两点不好的地方,引用尤大的话来说就是:
方案2: 该方法是通过$once这个事件侦听器器在定义完定时器之后的位置来清除定时器。以下是完整代码:
mounted: function () {
const timer = setInterval(() =>{
// 某些定时器操作
}, 500);
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
})
}
mounted: function () {
this.attachDatepicker('startDateInput')
this.attachDatepicker('endDateInput')
},
methods: {
attachDatepicker: function (refName) {
var picker = new Pikaday({
field: this.$refs[refName],
format: 'YYYY-MM-DD'
})
this.$once('hook:beforeDestroy', function () {
picker.destroy()
})
}
}
综合来说,我们更推荐使用方案2,使得代码可读性更强,一目了然。如果不清楚$once、$on、$off
的使用,这里送上官网的地址教程,在程序化的事件侦听器那里。