在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 }