方法1:实例中保存定时器
data() {
return {
timer: null // 定时器名称
}
},
然后 method 中这样使用定时器:
timerSet(){
this.timer = setInterval(() => {
// 某些操作
}, 1000)
return this.timer
}
可以在 created 或 mounted 中调用
this.timerSet()
最后在 beforeDestroy()生命周期内清除定时器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
方法2:使用 $once
const timer = setInterval(() =>{
// 某些定时器操作
}, 500);
// 通过 $once 来监听定时器,在 beforeDestroy 钩子可以被清除。
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
})
mounted: function () {
var picker = new Pikaday({
field: this.$refs.input,
format: 'YYYY-MM-DD'
})
this.$once('hook:beforeDestroy', function () {
picker.destroy()
})
}
方法1 需要在实例中保存这个 timer,可以通过 this 访问到;
方法2 不需要在实例中保存,不能用 this 访问,但是可以同时被多个元素绑定;
原文链接:
https://blog.csdn.net/qq_21132509/java/article/details/83504522
