在web頁面實現相似於瀏覽器的頁籤功能,使用vue的keep-alive組件作緩存vue
基本實現以下:web
1.將須要作緩存的視圖用keep-alive包裹vuex
<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); });
這裏使用了延時器是因爲不作延時就沒法生效。spa
vuex的相關設置code
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 }