1.查看app.vue文件,這個是重點,不能忘記加(我就是忘記加了keep-alive)
2.查看router.js
3.在需要緩存的頁面加入如下代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
beforeRouteEnter(to, from, next) {
if
(from.name ==
'creditInformation'
|| from.name ==
'cityList'
) {
to.meta.isBack =
true
;
}
next();
},
activated() {
this
.getData()
this
.$route.meta.isBack =
false
this
.isFirstEnter =
false
},
|
附上鈎子函數執行順序:
-
不使用keep-alive
beforeRouteEnter --> created --> mounted --> destroyed -
使用keep-alive
beforeRouteEnter --> created --> mounted --> activated --> deactivated
再次進入緩存的頁面,只會觸發beforeRouteEnter -->activated --> deactivated 。created和mounted不會再執行。
摘自:https://www.cnblogs.com/helloyong123/p/13427275.html
4、include 與 exclude
當組件在 keep-alive 內被切換,它的 activated 和 deactivated 這兩個生命周期鈎子函數將會被對應執行。
include - 字符串或正則表達式。只有匹配的組件會被緩存。
exclude - 字符串或正則表達式。任何匹配的組件都不會被緩存。
1
2
3
4
5
6
7
8
9
10
11
12
|
<!-- 逗號分隔字符串 -->
<keep-alive include=
"a,b"
>
<component :is=
"view"
></component>
</keep-alive>
<!-- 正則表達式 (使用 `v-bind`) -->
<keep-alive :include=
"/a|b/"
>
<component :is=
"view"
></component>
</keep-alive>
<!-- 數組 (使用 `v-bind`) -->
<keep-alive :include=
"['a', 'b']"
>
<component :is=
"view"
></component>
</keep-alive>
|
匹配首先檢查組件自身的 name 選項,如果 name 選項不可用,則匹配它的局部注冊名稱 (父組件 components 選項的鍵值)。匿名組件不能被匹配。
5. 監聽路由變化
使用 watch 監聽路由變化,但是我發現監聽路由只有在組件被 keep-alive 包裹時才生效,未包裹時不生效,原因不明,理解的小伙伴請留言告訴我!
1
2
3
4
5
|
watch: {
'$route'
(to, from) {
// 對路由變化作出響應...
}
}
|
beforeRouteUpdate 這個鈎子目前我發現還不能用,不知道哪里出錯。
1
2
3
4
|
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
|
6、可以在不想進行緩存的組件中,可以添加該方法來設置組件不被keep-alive進行緩存:
原理是 在路由跳轉之前 對頁面進行銷毀 清除緩存 實現下次進來時頁面數據從新加載
deactivated() { this.$destroy(); }
摘自:https://blog.csdn.net/weixin_44301166/article/details/107355361