一、页面权限
1、关于页面权限控制的实现
antd pro 项目中的 src/access.ts,该文件中 export default 一个函数用于定义用户拥有的权限,例如:
//routes.js 文件部分代码
export default [
//...此处省略n行代码
{
path: '/home',
component: './home',
name: '首页',
access: 'home',
icon: 'home',
},
{
path: '/workplace',
component: './home/workplace',
access: 'workplace',
name: '工作台',
icon: 'desktop',
}
]
// src/access.ts
export default function (initialState) {
return {
home: true,
workplace: false,
};
}
🎍>_>我将routes.js文件中的access字段的值称为关键字,当然如果你不想用access,也可以取其它名称
当src/access.ts文件返回的对象中返回的关键字的值为false时,对应页面无访问权限,反之则有
2、页面权限控制>>实现方法
1、使用initHandleRoutes 方法,将routes.js中的设置了access的页面权限初始化为无访问权限
2、根据菜单数据,将有权限的页面对应的关键字的值改写为true,可以把功能权限的关键字和值一起写进来
3、记得在创建菜单时将页面的关键字传给后台
import routes from '../config/routes';
/**
* @see https://umijs.org/zh-CN/plugins/plugin-access
* */
export default function access(initialState) {
const { currentUser } = initialState || {};
const initPageAuthority = initHandleRoutes(routes);
//菜单数据
const menuData = currentUser?.menuData || [];
//下面的方法可以自行更具获取的菜单数据写
//将有权限的页面对应的关键字的值改写为true
//可以把功能权限的关键字和值一起写进来
//const authority = filterAccessMenu(initPageAuthority, menuData);
console.log('authority:', authority);
return authority;
}
/**初始化路由页面权限
* @description 初始化拥有access字段值且不为空的path路径的访问权限为false
*/
const initHandleRoutes = (menu) => {
let body = {};
for (let i = 0; i < menu.length; i++) {
if (menu[i].access) {
body[menu[i].access] = false;
}
if (menu[i].routes && menu[i].routes.length > 0) {
let menu2 = menu[i].routes;
for (let j = 0; j < menu2.length; j++) {
if (menu2[j].access) {
body[menu2[j].access] = false;
}
}
}
}
return body;
};
二、页面内权限
页面内权限你需要用到 useAccess,
注意:该方案你需要提前设定好各个功能的关键字,并写死在代码中
例子如下:
import { useAccess} from 'umi';
//获取access.js文件中access方法返回的权限对象
const access = useAccess();
const perms = 'sys:user:remove'; //删除功能的关键字
//使用方案一
const deleteRender = () =>(access[perms] ? <Button>删除</Button>: null)
//方案二,提前将其封装成一个组件,然后用它去包裹你的功能按钮
<CheckButtonPerms key={'5'} perms={'sys:user:remove'}>
<a key={'delete'} onClick={() => { }}>删除</a>
</CheckButtonPerms>