方法一、在生命周期函數(shù)beforeDestroy中清除?
data() {
return {
timer: null;
};
},
created() {
// 設置定時器,5s執(zhí)行一次
this.timer = setInterval(() => {
console.log('setInterval');
}, 5000);
}
beforeDestroy () {
//清除定時器
clearInterval(this.timer);
this.timer = null;
}
方法二、使用hook:beforedestroy(推薦)
created() {
// 設置定時器,5s執(zhí)行一次
let timer = setInterval(() => {
console.log('setInterval');
}, 5000);
// 離開當前頁面時銷毀定時器
this.$once('hook:beforeDestroy', () => {
clearInterval(timer);
timer = null;
})
}
該方法與在生命周期鉤子beforeDestroy中清除定時器的操作原理一樣,但更有優(yōu)勢
1.無需在vue實例上定義定時器,減少不必要的內存浪費
2.設置和清除定時器的代碼放在一塊,可讀性維護性更好
三、beforeDestroy函數(shù)沒有觸發(fā)的情況
1、原因
<router-view>外層包裹了一層<keep-alive>
< keep-alive > 有緩存的作用,可以使被包裹的組件狀態(tài)維持不變,當路由被 keep-alive 緩存時不走 beforeDestroy 生命周期。被包含在 < keep-alive > 中創(chuàng)建的組件,會多出兩個生命周期鉤子: activated 與 deactivated。
activated
在組件被激活時調用,在組件第一次渲染時也會被調用,之后每次keep-alive激活時被調用。
deactivated
在組件失活時調用。
2、解決方案
借助 activated 和 deactivated 鉤子來設置和清除定時器
(1)生命周期鉤子文章來源:http://www.zghlxwxcb.cn/news/detail-408436.html
created() {
// 頁面激活時設置定時器
this.$on("hook:activated", () => {
let timer = setInterval(()=>{
console.log("setInterval");
},1000)
})
// 頁面失活時清除定時器
this.$on("hook:deactivated", ()=>{
clearInterval(timer);
timer = null;
})
}
(2)hook文章來源地址http://www.zghlxwxcb.cn/news/detail-408436.html
data() {
return {
timer: null // 定時器
}
},
activated() {
// 頁面激活時開啟定時器
this.timer = setInterval(() => {
console.log('setInterval');
}, 5000)
},
deactivated() {
// 頁面關閉(路由跳轉)時清除定時器
clearInterval(this.timer)
this.timer = null
},
到了這里,關于VUE設置和清除定時器的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!