使用鈎子函數對定時器進行清理,失敗了,
1、在data中聲明要設置的定時器名稱:
data() {
return {
timer: null // 定時器名稱
}
},
2、在mounted中創建定時器:
this.timer = (() => {
// 某些操作
}, 5000)復制代碼
3、在頁面注銷時清理定時器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}復制代碼
然鵝,並沒什么卵用,在切換頁面后,定時任務依然頑強的奔跑着。
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
console.log(this.timer) //輸出為: null,但是任務依然在繼續運行
}復制代碼
經過在各大論壇一番查找發現:
通過$once這個事件偵聽器在定義完定時器之后的位置來清除定時器:
const timer = setInterval(() =>{
// 某些定時器操作
}, 5000);
// 通過$once來監聽定時器
// 在beforeDestroy鈎子觸發時清除定時器
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
})
哇,成功了...
