首先是侧边栏根据不同的权限过滤,然后侧边栏能按照不同权限显示了。但是用户在url输入地址仍然能访问,所以需要鉴权
一.侧边栏过滤思路
1.通过路由的meta下的auth存储权限数组
const routes = [
{
path: '/',
redirect: isClient ? '/clientApp' : '/screen',
meta: {
title: '',
auth: ['COLLECT_ADMIN', 'SECOND_CHECK', 'COLLECT', 'FIRST_CHECK', 'ADMIN', 'SURVEY_ADMIN'],
icon: '',
env: 'public',
},
},
{
path: '/Login',
name: 'Login',
component: () => import('../views/Login.vue'),
meta: {
title: '登录页',
auth: ['COLLECT_ADMIN', 'SECOND_CHECK', 'COLLECT', 'FIRST_CHECK', 'ADMIN', 'SURVEY_ADMIN'],
icon: '',
env: 'public',
},
},
{
path: '/screen',
name: 'Screen',
component: () => import('../views/Screen'),
meta: {
title: '大屏',
auth: ['COLLECT_ADMIN', 'SECOND_CHECK', 'COLLECT', 'FIRST_CHECK', 'ADMIN', 'SURVEY_ADMIN'],
icon: '',
env: 'web',
},
},
{
path: '/401',
name: '401',
component: () => import('../views/ErrorPage/401.vue'),
meta: {
title: '',
auth: ['COLLECT_ADMIN', 'SECOND_CHECK', 'COLLECT', 'FIRST_CHECK', 'ADMIN', 'SURVEY_ADMIN'],
icon: '',
env: 'public',
},
},
clientAppRouter,
adminRouter,
]
2.侧边栏过滤渲染
const createRoutes = async (routes) => {
const { data } = await http.user.getUserInfo()
//获取用户权限数组
const sysRoleIdArr = data.sysRoleIdArr
//routes是路由列表,根据item.meta.auth和sysRoleIdArr求交集进行权限过滤,得到对应用户权限的数组
const res = routes
.map((item) => {
const isPass = _.intersection(item.meta.auth, sysRoleIdArr)
if (isPass.length) {
return item
}
})
.filter((item) => item)
return await res
}
const filterRouteList = ref([])
//过滤后赋值渲染
createRoutes(props.routeList).then((res) => {
filterRouteList.value = res
})
<el-menu-item
v-for="item of filterRouteList"
v-show="item.meta.icon"
:key="item.name"
:index="item.name"
@click="changeRouter(item)"
>
<SvgIcon :name="item.meta.icon" style="margin-right: 14px; width: 12px; height: 12px" />
<template #title>{{ item.meta.title }}</template>
</el-menu-item>
二.路由鉴权
router.beforeEach(async (to, from, next) => {
const isLogin = localStorage.getItem('AUTH_ACCESS_TOKEN')
if (to.path == '/Login') {
next()
} else {
//先判断是否登录
if (isLogin) {
const { data } = await http.user.getUserInfo()
const sysRoleIdArr = data.sysRoleIdArr
//to表示要跳到的页面进行鉴权
const isPass = _.intersection(to.meta.auth, sysRoleIdArr)
//如果权限匹对成功则显示,否则显示404页面
isPass.length ? next() : next('/401')
} else if (!isLogin) {
next('/Login')
}
}
})
三.简单效果哈