1.在keep-alive中直接添加 include谦絮,cachedViews(Array類型:包含vue文件的組件name都將被緩存起來)题诵;反之exclude則是不包含;
注意:所有.vue組件文件都必須附上name屬性2阒濉P远А!建議用vuex管理cachedViews
<keep-alive :include="cachedViews">
<router-view></router-view>
</keep-alive>
2.監(jiān)測(cè)$router的變化叫胖;
watch: {
// 如果路由有變化草冈,會(huì)再次執(zhí)行該方法
"$route": "fetchDate"
}
但是會(huì)在頁面離開時(shí)再次執(zhí)行fetchDate,并不是我們需要的,所以可以在to和from上添加執(zhí)行邏輯怎棱,但也是十分的麻煩
//route (to, from) {
if(list.indexOf(from.path) > -1){ //自行添加邏輯,list為你不想有緩存的路徑
this.getData()
}
}
}
3.在添加keep-alive后會(huì)增加兩個(gè)生命周期mounted>activated拳恋、離開時(shí)執(zhí)行deactivated凡资,路由的進(jìn)入和切換回相應(yīng)的觸發(fā)activated和deactivated,這樣就可以在每次入路由執(zhí)行更細(xì)致的操作了
//如果是服務(wù)端渲染就算了
activated() {
//只刷新數(shù)據(jù)谬运,不改變整體的緩存
this.fetchDate();
}
4.還有更簡單粗暴的
//我就笑笑不說話
<div>
<keep-alive>
<router-view v-if="route.meta.keepAlive"></router-view>
</div>
5.還有種情況隙赁,在不同路由應(yīng)用了相同的vue組件
{path:'aaa',component:Mompage,name:'mom'},
{path:'bbb',component:Mompage,name:'momPlus'}
默認(rèn)情況下當(dāng)這兩個(gè)頁面切換時(shí)并不會(huì)觸發(fā)vue的created或者mounted鉤子,需要手動(dòng)的watch:$router(又回到上面的步驟)梆暖,或者在router-view上加上唯一值伞访。
//隨便抄一段代碼過來
<router-view :key="key"></router-view>
computed: {
key() {
return this.route.name + +new Date(): this.$route + +new Date()
}
}