实现思路
- 在路由配置中,为需要根据权限判断缓存的路由添加自定义元信息,例如
meta: { cache: true, requirePermission: '特定权限标识' }
。
- 在
beforeEach
路由守卫中,获取当前用户权限信息。
- 根据用户权限和路由元信息判断该组件是否应该被缓存。
- 在使用
keep - alive
时,通过动态绑定 include
或 exclude
属性来控制组件的缓存。
关键代码示例
- 路由配置
const routes = [
{
path: '/example',
name: 'Example',
component: () => import('@/views/Example.vue'),
meta: {
cache: true,
requirePermission: 'admin' // 假设只有admin权限可缓存
}
}
]
- 路由守卫
import router from './router'
import store from './store' // 假设权限信息存储在vuex中
router.beforeEach((to, from, next) => {
const userPermission = store.getters.userPermission // 获取用户权限
if (to.meta.cache && to.meta.requirePermission) {
if (userPermission.includes(to.meta.requirePermission)) {
// 用户有权限,添加到缓存列表
if (!store.state.cacheComponents.includes(to.name)) {
store.commit('addCacheComponent', to.name)
}
} else {
// 用户无权限,从缓存列表移除
if (store.state.cacheComponents.includes(to.name)) {
store.commit('removeCacheComponent', to.name)
}
}
}
next()
})
- Vuex配置
const state = {
cacheComponents: []
}
const mutations = {
addCacheComponent(state, componentName) {
state.cacheComponents.push(componentName)
},
removeCacheComponent(state, componentName) {
state.cacheComponents = state.cacheComponents.filter(name => name!== componentName)
}
}
const getters = {
cacheComponents: state => state.cacheComponents
}
export default {
state,
mutations,
getters
}
- 使用
keep - alive
<template>
<keep - alive :include="cacheComponents">
<router - view />
</keep - alive>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['cacheComponents'])
}
}
</script>