前言碎碎念
刚接手React项目,遇到一个需求要根据用户角色展示不同的页面,由于对react不是很熟悉,导致下了班还在查文档,项目里用到了@umijs/plugin-access。
@umijs/plugin-access 是一个 Umi 插件,用于根据用户角色来展示不同的页面。它提供了一种简便的方式来控制页面的访问权限。
实现
- 登陆之后用useModel手动设置 initialState 的值
import {useModel} from 'umi';
const {initialState, setInitialState} = useModel('@@initialState');
//登陆之后拿到userInfo
await fetchUserInfo(userInfo);
const fetchUserInfo = async (value) => {
if (value) {
await setInitialState((s) => ({...s, currentUser: value}));
}
};
- 项目中的src目录下创建access.ts文件
/**
* @see https://umijs.org/zh-CN/plugins/plugin-access
* */
// 角色Id为17是超级管理员,18为管理员,其余为普通用户
export default function access(initialState: { currentUser?: API.CurrentUser | undefined }) {
const {currentUser} = initialState || {};
return {
login: currentUser !== undefined,
canAccess: currentUser ? currentUser.roleId == '17' || currentUser.roleId == '18' : undefined,
canAdminAccess: currentUser ? currentUser.roleId == '17' : undefined,
}
}
3在你的路由配置文件中,你可以通过设置 access 属性来控制页面的访问权限。例如:
import access from '@/access';
export default [
{
path: '/home',
component: '@/pages/index',
},
{
name: '系统管理',
path: '/systemManage',
component: './SystemManage',
authority: ['admin'],
access: 'canAccess',
routes: [
{
name: '数据管理',
path: './data',
component: './SystemManage/dataManage',
},
{
name: '用户管理',
path: './user',
component: './SystemManage/userManage',
access: 'canAdminAccess'
}
],
},
// 其他路由配置...
];
这样就可以根据用户角色来展示不同的页面了。当用户的角色为 管理员 时,可以访问设置了 access: ‘canAccess’ 属性的页面;当用户的角色为 超级管理员 时,可以访问设置了 access: ‘canAdminAccess’ 属性的页面,否则访问受限。