首先確認< router-view >外層是否有包裹了一層< keep-alive >
如果有包裹:
<template>
<div>
<keep-alive>
<router-view />
</keep-alive>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
在data中:
data () {
return {
timer: null // 定時器
}
},
- 1
- 2
- 3
- 4
- 5
在activated中設置定時器:
activated () {
this.timer = setInterval(() => {
// 定時器中執行的代碼
}, 30000)
},
- 1
- 2
- 3
- 4
- 5
在deactivated中清除定時器:
deactivated () {
// 頁面關閉(路由跳轉)時清除定時器
clearInterval(this.timer)
this.timer = null
},
- 1
- 2
- 3
- 4
- 5
< keep-alive >作用:
< keep-alive > 可以使被包含的組件狀態維持不變,即便是組件切換了,其內的狀態依舊維持在內存之中。在下一次顯示時,也不會重現渲染(有緩存的作用)。
被包含在 < keep-alive > 中創建的組件,會多出兩個生命周期的鈎子: activated 與 deactivated
activated
在組件被激活時調用,在組件第一次渲染時也會被調用,之后每次keep-alive激活時被調用。
deactivated
在組件被停用時調用。
注意:只有組件被 keep-alive 包裹時,這兩個生命周期才會被調用,如果作為正常組件使用,是不會被調用,以及在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive中,這兩個鈎子依然不會被調用!另外在服務端渲染時此鈎子也不會被調用的。
如果沒有包裹
在data中:
data () {
return {
timer: null // 定時器
}
},
- 1
- 2
- 3
- 4
- 5
在mounted中設置定時器:
mounted() {
this.timer = setInterval(() => {
// 定時器中執行的代碼
}, 30000)
},
- 1
- 2
- 3
- 4
- 5
在beforeDestroy中清除定時器:
beforeDestroy() {
// 頁面關閉(路由跳轉)時清除定時器
clearInterval(this.timer)
this.timer = null
},