vue的keep-alive實現框架頁簽功能


在web頁面實現類似於瀏覽器的頁簽功能,使用vue的keep-alive組件做緩存

基本實現如下:

1.將需要做緩存的視圖用keep-alive包裹

<keep-alive :include="keepAliveComponents">
              <router-view></router-view>
          </keep-alive>

2.視圖通過路由配置。需要緩存的組件在meta的keepAlive設為true,注意需要設置name

const routes = [
    {
        path: "/talentPool",
        component: TalentPool,
        name: 'TalentPool',
        meta: {
            keepAlive: true,
            title: "人才池",
            pageCode: "TalentPool"
        }
    }
];

3.如果需要動態更改緩存組件的,即有的情景下需要緩存,有的情景下不需要緩存,則需要做一個動態數組去控制

分別在路由跳轉前和跳轉后做處理,這里使用了vuex,需要緩存的組件名數組存在store里(注意是存的是組件名,keep-alive的include方式識別的是組件名)

router.beforeEach((to, from, next) => {
    /* 路由發生變化修改頁面title */
    if (to.meta.title) {
        document.title = to.meta.title;
    }
    if(from.path == '/'){
        to.name && store.commit('keepAlive/noKeepAlive', to.name);
        if(to.name == 'FloatingListMyRecommend'){
            store.commit('keepAlive/noKeepAlive', 'FloatingListRecommendToMe');
        }
    }
    next();
});

 

router.afterEach((to, from) => {
    setTimeout(() => {
        if(to.name !== 'WorkTableHome'){
            to.name && store.commit('keepAlive/keepAlive', to.name);
        }

    }, 1000);
});

這里使用了延時器是由於不做延時就無法生效。

vuex的相關設置

 

 

const state = {
    keepAliveComponents: []//需要緩存的數組
}

const getters = {
    keepAliveComponents(state){
        return state.keepAliveComponents;
    }
}

const actions = {
    invokeKeepAlive({ commit, state }, component) {
        commit('keepAlive', component);
    },
    invokeNoKeepAlive({ commit, state }, component) {
        commit('noKeepAlive', component);
    },
}

const mutations = {
    keepAlive (state, component) {
        !state.keepAliveComponents.includes(component) &&
            state.keepAliveComponents.push(component)
    },
    noKeepAlive (state, component) {
        const index = state.keepAliveComponents.indexOf(component)
        index !== -1 &&
            state.keepAliveComponents.splice(index, 1)
    }

}

export default {
    namespaced:true,
    state,
    getters,
    actions,
    mutations
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM