做了一个分用户权限访问的简单路由管理,最开始查阅了很多大佬的博文,但是总是数据丢失,疯狂写了好多log输出才找到问题出在哪里,记录一下吧,需要说明一下的我写的只是部分代码,可能有遗漏,但是只是我没写在博文里,项目我是运行成功了的,但是因为融合了前后端,还有我的其他项目所以不能全放就是了,仅供参考,加上一些我自己踩的坑,着重修改的部分,我也是前端小白的说,大佬们轻喷(其实也不会有人看这个吧),参考文献放在前面,
前端实现:不同角色登入展示不同页面效果\]([https://blog.csdn.net/m0_74824687/article/details/144729934](https://blog.csdn.net/m0_74824687/article/details/144729934 "https://blog.csdn.net/m0_74824687/article/details/144729934"))
\[[手摸手,带你用vue撸后台](https://segmentfault.com/a/1190000009275424 "手摸手,带你用vue撸后台")\]([https://segmentfault.com/a/1190000009275424](https://segmentfault.com/a/1190000009275424 "https://segmentfault.com/a/1190000009275424"))
需求是,使用管理员访问的时候能看到其他页面和用户管理页面,使用其他普通用户访问的时候只有其他页面,看不见用户管理页面
## 首先就是vue前端页面
导航栏上加上v-if
用户管理
加了一个role功能,因为我设定是管理员和技术部的人员可以查看,其他部门都是普通用户。
```html
const isAdmin = computed(() => {
if (authStore.role) {
return authStore.role === 'admin';
}
// 从localStorage获取角色信息
const role = localStorage.getItem('role');
return role === 'admin';
});
```
## 接着是router
router/index.js里面加上路由拦截
```html
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
const expiresAt = localStorage.getItem('expiresAt');
const role = localStorage.getItem('role');
const isAuthenticated = token && expiresAt && new Date().getTime() < new Date(expiresAt).getTime();
const isAdmin = role === 'admin';
if (to.meta.requiresAuth && !isAuthenticated) {
return next('/login');
}
if (to.path === '/login' && isAuthenticated) {
return next('/');
}
if (to.meta.requiresAdmin && !isAdmin) {
alert('您没有权限访问该页面');
return next('/');
}
next();
}
```
并且让分用户访问时**初始化前端路由系统,重新渲染导航栏**
```html
const router = createRouter({
history: createWebHashHistory(),
routes: routes
});
```
我映射的逻辑,分成两种角色
```html
mapDepartmentToRole(department) {
if (typeof department !== 'string') return 'editor';
const normalized = department.trim();
if (normalized === '管理员' || normalized === '技术部' ||
normalized.toLowerCase() === 'admin') {
return 'admin';
}
if (normalized === '管理部' || normalized === '运维部' ||
normalized === '销售部') {
return 'editor';
}
// 默认普通用户
return 'editor';
},
```
## 然后是后端部分
如果登录成功了获取部门字段
```html
if (result.success) {
res.json({
success: true,
token: result.token,
username: result.username,
department: result.department,
expiresAt: result.expiresAt
});
}
```
service里面密码匹配,匹配成功后返回的也要加部门
```html
return {
success: true,
token,
username,
department: admin.department || '管理员',
expiresAt: new Date(expirationTime).toISOString()
};
```