方法一:使用生命周期函数beforeDestory
data() {
return {
timer: null
}
},
methods: {
getList().then(res => {
this.timer = setInterval(() => {
console.log('1s打印')
},1000)
})
},
beforeDestory() {
clearInterval(this.timer)
this.timer = null
}
方法二:使用hook:beforeDestory
created() {
let timer = setInterval(() => {
console.log('1s打印')
},1000);
this.$once('hook:beforeDestory', () => {
clearInterval(this.timer)
timer = null
})
}
使用hook的优势在于无需在vue实例上定义定时器,减少不必要的内存浪费而且设置和清除定时器的代码放在一块,可读性维护性更好
评论 (0)