先上图:
整个角色管理是如何做的吗?
首先你要处理后端,要先把角色存到用户那。
这是用户管理部分的内容:
可以看到一个用户是有多个角色的。
看到没有,存的是数组
数组的是一个 role 对象
role 对象是这样:
主要是存一个 name 就好。permissions 是权限列表。
import { Request, Response } from 'express';
import Role from '../models/role';
import handleAsync from '../utils/handleAsync';
// Build query based on query parameters
const buildQuery = (queryParams: any): any => {
const query: any = {};
if (queryParams.name) {
query.name = { $regex: queryParams.name, $options: 'i' };
}
return query;
};
// 获取所有角色
const getRoles = handleAsync(async (req: Request, res: Response) => {
const { current = '1', pageSize = '10' } = req.query;
const query = buildQuery(req.query);
const roles = await Role.find(query)
.populate('permissions')
.sort('-createdAt') // Sort by creation time in descending order
.skip((+current - 1) * +pageSize)
.limit(+pageSize)
.exec();
res.json({
success: true,
data: roles,
});
});
// 根据 ID 获取角色
const getRoleById = handleAsync(async (req: Request, res: Response) => {
const role = await Role.findById(req.params.id).exec();
if (!role) {
res.status(404);
throw new Error('Role not found');
}
res.json({
success: true,
data: role,
});
});
// 添加新角色
const addRole = handleAsync(async (req: Request, res: Response) => {
const newRole = new Role({
...req.body,
});
const savedRole = await newRole.save();
res.json({
success: true,
data: savedRole,
});
});
// 更新角色
const updateRole = handleAsync(async (req: Request, res: Response) => {
const { id } = req.params;
const updatedRole = await Role.findByIdAndUpdate(
id,
{ ...req.body },
{ new: true },
).exec();
if (!updatedRole) {
res.status(404);
throw new Error('Role not found');
}
res.json({
success: true,
data: updatedRole,
});
});
// 删除角色
const deleteRole = handleAsync(async (req: Request, res: Response) => {
const { id } = req.params;
const role = await Role.findByIdAndDelete(id).exec();
if (!role) {
res.status(404);
throw new Error('Role not found');
}
res.json({
success: true,
data: { message: 'Role deleted successfully' },
});
});
// 批量删除角色
const deleteMultipleRoles = handleAsync(async (req: Request, res: Response) => {
const { ids } = req.body;
await Role.deleteMany({
_id: { $in: ids },
}).exec();
res.json({
success: true,
message: `${ids.length} roles deleted successfully`,
});
});
export {
getRoles,
getRoleById,
addRole,
updateRole,
deleteRole,
deleteMultipleRoles,
};
这是后端代码,就是增删改查。比较容易理解。
前端:
import { useIntl } from '@umijs/max';
import React, { Key, useState } from 'react';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { Form, Input, Spin, Tree } from 'antd';
import useQueryList from '@/hooks/useQueryList';
import { FormInstance } from 'antd/es/form';
import { Permission } from '@/apiDataStructures/ApiDataStructure';
interface Props {
form?: FormInstance<any>;
newRecord?: boolean;
onFinish: (formData: any) => Promise<void>;
values?: any;
}
const BasicForm: React.FC<Props> = ({ newRecord, onFinish, values }) => {
const intl = useIntl();
const { items: permissionGroups, loading } = useQueryList('/permission-groups/list');
const [expandedKeys, setExpandedKeys] = useState<Key[]>([]);
const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
const [checkedKeys, setCheckedKeys] = useState<Key[] | { checked: Key[]; halfChecked: Key[] }>(
values.permissions?.map((permission: Permission) => `${permission._id}`) ?? [],
);
const [selectedKeys, setSelectedKeys] = useState<Key[]>([]);
const onExpand = (expandedKeysValue: Key[]) => {
setExpandedKeys(expandedKeysValue);
setAutoExpandParent(false);
};
const onCheck = (checkedKeysValue: Key[] | { checked: Key[]; halfChecked: Key[] }) => {
setCheckedKeys(checkedKeysValue);
console.log('checkedKeysValue', checkedKeysValue);
};
const onSelect = (selectedKeysValue: Key[]) => {
setSelectedKeys(selectedKeysValue);
};
return (
<ProForm
initialValues={{
...values,
permissions: values?.permissions?.map((permission: Permission) => permission._id),
}}
onFinish={async (values) => {
await onFinish({
...values,
permissions: checkedKeys,
});
}}
>
<ProForm.Group>
<ProFormText
rules={[{ required: true, message: intl.formatMessage({ id: 'enter_name' }) }]}
width="md"
label={intl.formatMessage({ id: 'name' })}
name="name"
/>
<ProForm.Item name="permissions" label={intl.formatMessage({ id: 'permission_choose' })}>
<Spin spinning={loading}>
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={permissionGroups} // Use filtered top-level groups
fieldNames={{ title: 'name', key: '_id', children: 'children' }}
/>
</Spin>
</ProForm.Item>
</ProForm.Group>
{!newRecord && (
<Form.Item name="_id" label={false}>
<Input type="hidden" />
</Form.Item>
)}
</ProForm>
);
};
export default BasicForm;
https://www.qiuzhi99.com/playlists/antdpromakemoney.html