vue keep-alive實作動态緩存以及緩存銷毀
文字連結位址vue keep-alive實作動态緩存以及緩存銷毀
需求來源及描述
背景管理系統中,左側為功能菜單欄,點選菜單清單,右側顯示該菜單的功能頁面,本來是一個非常簡單的背景管理系統布局,現在增加了tabs菜單按鈕;
點選左側菜單欄時,右側頁面頭部header顯示目前的頁面标題,形成一個tabs清單,點選可切換頁面内容和關閉tabs;
需求要求,點選左側時,右側顯示頁面内容,同時右側header增加該頁面的tabs,點選tabs可以切換頁面,但頁面内容不重新整理,點選左側菜單時,右側内容重新整理;
初步解決
第一想到的時利用vue的功能元件
<keep-alive>
<router-view/>
</keep-alive>
此時隻能實作緩存,但是不能根據需求實作動态緩存
解決方案
利用
include
來判斷需要緩存的路由元件,在根據點選狀态更新
include
<!-- html -->
<keep-alive :include="keepAliveList">
<router-view :key="$route.fullPath"/>
</keep-alive>
利用計算屬性和vuex擷取緩存清單
<!-- vuex -->
state: {
keepAliveList:'',//儲存緩存的清單
},
mutations: {
setKeepAliveLists(state,arrListString){
state.keepAliveList = arrListString;
},
}
<!-- 視圖元件中 -->
computed:{
keepAliveList(){
// 擷取緩存的路由清單
return this.$store.state.keepAliveList;
}
}
生成緩存清單,清單的值為各元件中name的值集合拼接的字元串
this.$store.commit('setKeepAliveLists',routerComponentNameList.join())
點選左側菜單欄時,更新緩存清單
<!-- 點選左側菜單的事件函數 -->
handleSelect(name) {
if(this.routerNameMap.has(name)){//如果目前點選的路由已經在緩存清單中,則先清除緩存清單,再添加;
this.resetKeepAive(name,this.keepAliveList);//删除緩存路由
this.tabChangeRoute(name);//切換路由
} else {
this.routerNameMap.add(name)
this.tabChangeRoute(name);
}
},
// 更新要緩存的路由清單
resetKeepAive(name,cacheList) {
const conf = this.keepAliveList;
let arr = cacheList.split(',');
if (name && typeof name === 'string') {
let i = arr.indexOf(name);
if (i > -1) {
arr.splice(i, 1);
this.$store.commit('setKeepAliveLists',arr.join());
this.$nextTick(() => {//添加緩存路由
this.$store.commit('setKeepAliveLists',conf);
})
}
}
}
點選右側tabs關閉标簽删除緩存
removeTab(name){
// 點選tab上的關閉按鈕,清除目前路由的緩存
this.routerNameMap.delete(name);
this.resetKeepAive(name,this.keepAliveList);//删除緩存路由
}
下面為主要代碼,監聽目前路由是否被移除緩存,如果移除緩存則需要銷毀該元件,否則内容中的緩存元件會越來越來,影響使用性能;
建立一個
mixin.js
檔案,然後引入到需要被動态緩存的路由元件中即可;
// 路由緩存管理
export default {
computed: {
keepAliveConf(){
return this.$store.state.keepAliveList;
}
},
watch:{
keepAliveConf(e){
// 監聽緩存清單的變化,如果緩存清單中沒有目前的路由或元件則在緩存中銷毀該執行個體
let name = this.$options.name;
if(!e.split(',').includes(name)) {
this.$destroy()
}
}
},
}