项目中,使用定时器的普遍写法,是定义定时器,然后在beforeDestroy中销毁定时器
data() {
return {
timeInterval: null
}
},
beforeDestroy() {
if (this.timeInterval) {
clearInterval(this.timeInterval)
}
},
methods: {
timingGetInfo() {
if (this.timeInterval) {
clearInterval(this.timeInterval)
}
if (this.form.cutoverNum) {
this.timeInterval = setInterval(() => {
// 相关操作
}, 5000)
}
}
}
以上写法,会觉得定时器的相关代码,比较分散,不易管理,推荐大家试试以下写法:
methods: {
timingGetInfo() {
const timer = setInterval(() => {
// 相关操作
}, 5000)
// 通过$once监听定时器,将其在beforeDestroy清除
this.$once('hook:beforeDestroy', () => {
clearInterval(timer )
})
}
}