feat(@vben/web-antd): 优化角色模块和系统菜单

This commit is contained in:
Kven 2025-05-10 12:39:10 +08:00
parent 139aa926be
commit 8a5777c6bb
13 changed files with 310 additions and 552 deletions

View File

@ -1,8 +1,15 @@
import type { Recordable } from '@vben/types';
import { h } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { $te } from '@vben/locales';
import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { isFunction, isString } from '@vben/utils';
import { Button, Image } from 'ant-design-vue';
import { Button, Image, Popconfirm, Switch } from 'ant-design-vue';
import { $t } from '#/locales';
import { useVbenForm } from './form';
@ -55,6 +62,181 @@ setupVbenVxeTable({
);
},
});
vxeUI.renderer.add('CellSwitch', {
renderTableDefault({ attrs, props }, { column, row }) {
const loadingKey = `__loading_${column.field}`;
const finallyProps = {
checkedChildren: $t('common.enabled'),
checkedValue: true,
unCheckedChildren: $t('common.disabled'),
unCheckedValue: false,
...props,
checked: row[column.field],
loading: row[loadingKey] ?? false,
'onUpdate:checked': onChange,
};
async function onChange(newVal: any) {
row[loadingKey] = true;
try {
const result = await attrs?.beforeChange?.(newVal, row);
if (result !== false) {
row[column.field] = newVal;
}
} finally {
row[loadingKey] = false;
}
}
return h(Switch, finallyProps);
},
});
/**
*
*/
vxeUI.renderer.add('CellOperation', {
renderTableDefault({ attrs, options, props }, { column, row }) {
const defaultProps = { size: 'small', type: 'link', ...props };
let align = 'end';
switch (column.align) {
case 'center': {
align = 'center';
break;
}
case 'left': {
align = 'start';
break;
}
default: {
align = 'end';
break;
}
}
const presets: Recordable<Recordable<any>> = {
delete: {
danger: true,
text: $t('common.delete'),
},
edit: {
text: $t('common.edit'),
},
};
const operations: Array<Recordable<any>> = (
options || ['edit', 'delete']
)
.map((opt) => {
if (isString(opt)) {
return presets[opt]
? { code: opt, ...presets[opt], ...defaultProps }
: {
code: opt,
text: $te(`common.${opt}`) ? $t(`common.${opt}`) : opt,
...defaultProps,
};
} else {
return { ...defaultProps, ...presets[opt.code], ...opt };
}
})
.map((opt) => {
const optBtn: Recordable<any> = {};
Object.keys(opt).forEach((key) => {
optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
});
return optBtn;
})
.filter((opt) => opt.show !== false);
function renderBtn(opt: Recordable<any>, listen = true) {
return h(
Button,
{
...props,
...opt,
icon: undefined,
onClick: listen
? () =>
attrs?.onClick?.({
code: opt.code,
row,
})
: undefined,
},
{
default: () => {
const content = [];
if (opt.icon) {
content.push(
h(IconifyIcon, { class: 'size-5', icon: opt.icon }),
);
}
content.push(opt.text);
return content;
},
},
);
}
function renderConfirm(opt: Recordable<any>) {
let viewportWrapper: HTMLElement | null = null;
return h(
Popconfirm,
{
/**
* popconfirm用在固定列中时
*
* body或者表格视口区域作为弹窗容器时又会导致弹窗无法跟随表格滚动
*
*
*/
getPopupContainer(el) {
viewportWrapper = el.closest('.vxe-table--viewport-wrapper');
return document.body;
},
placement: 'topLeft',
title: $t('ui.actionTitle.delete', [attrs?.nameTitle || '']),
...props,
...opt,
icon: undefined,
onOpenChange: (open: boolean) => {
// 当弹窗打开时,禁止表格的滚动
if (open) {
viewportWrapper?.style.setProperty('pointer-events', 'none');
} else {
viewportWrapper?.style.removeProperty('pointer-events');
}
},
onConfirm: () => {
attrs?.onClick?.({
code: opt.code,
row,
});
},
},
{
default: () => renderBtn({ ...opt }, false),
description: () =>
h(
'div',
{ class: 'truncate' },
$t('ui.actionMessage.deleteConfirm', [
row[attrs?.nameField || 'name'],
]),
),
},
);
}
const btns = operations.map((opt) =>
opt.code === 'delete' ? renderConfirm(opt) : renderBtn(opt),
);
return h(
'div',
{
class: 'flex table-operations',
style: { justifyContent: align },
},
btns,
);
},
});
// 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化
// vxeUI.formats.add
@ -63,5 +245,12 @@ setupVbenVxeTable({
});
export { useVbenVxeGrid };
export type OnActionClickParams<T = Recordable<any>> = {
code: string;
row: T;
};
export type OnActionClickFn<T = Recordable<any>> = (
params: OnActionClickParams<T>,
) => void;
export type * from '@vben/plugins/vxe-table';

View File

@ -2,55 +2,72 @@ import { requestClient } from '#/api/request';
export namespace RoleApi {
export interface Role {
[key: string]: any;
name: string;
dataScope: string;
permissionIds: (number | undefined)[];
remark: string;
authorities: (number | undefined)[];
id?: string;
}
// 基础信息
export interface RoleRecord extends Role {
enabled: boolean;
deptId: string;
remark?: string;
createBy: string;
createTime: string;
createId: string;
// authorities: (number | undefined)[];
id: string;
}
export interface RoleListRecord extends RoleRecord {
export interface RoleListParams {
page: number;
size: number;
sort: string;
name?: string;
enabled?: boolean;
deptId?: string;
}
export interface RoleListRecord extends Role {
name: string;
}
}
// 查询所有的角色列表、
export function queryRoleList(data: any) {
// return axios.get('/api/rest/role',data);
return requestClient.get('/api/rest/role', { data });
export function queryRoleList(data: RoleApi.RoleListParams) {
// return axios.get('/rest/role',data);
return requestClient.get<Array<RoleApi.Role>>('/rest/role', { params: data });
}
// 切换启用状态
export function enabled(id: string) {
return requestClient.patch(`/api/rest/role/${id}/toggle`);
export function enabledRole(id: string) {
return requestClient.patch(`/rest/role/${id}/toggle`);
}
// 删除
export function removeRole(id: string) {
return requestClient.delete(`/api/rest/role/${id}`);
return requestClient.delete(`/rest/role/${id}`);
}
// 添加
export function createRole(data: RoleApi.Role) {
return requestClient.post(`/api/rest/role`, data);
return requestClient.post(`/rest/role`, data);
}
// 更新
export function updateRole(data: RoleApi.RoleRecord) {
return requestClient.patch(`/api/rest/role/${data.id}`, data);
export function updateRole(id: any, data: RoleApi.Role) {
return requestClient.patch(`/rest/role/${id}`, data);
}
// 获取详情
export function getDetail(id: string) {
return requestClient.get<RoleApi.RoleRecord>(`/api/rest/role/${id}`);
return requestClient.get<RoleApi.Role>(`/rest/role/${id}`);
}
// export function queryRoles(params?: ListParams<Partial<RoleRecord>>) {
// return queryList<RoleRecord>(`/api/rest/role/query`, params);
export const queryMenuList = (data: string) => {
return requestClient.get('/rest/menu/tree', {
params: {
name: data,
},
});
};
// export function queryRoles(params?: ListParams<Partial<Role>>) {
// return queryList<Role>(`/rest/role/query`, params);
// }

View File

@ -1,18 +0,0 @@
import type { RouteRecordRaw } from 'vue-router';
import { RiDept } from '@vben/icons';
const routes: RouteRecordRaw[] = [
{
name: 'dept',
path: '/dept',
component: () => import('#/views/dept/list.vue'),
meta: {
icon: RiDept,
title: '部门管理',
order: 5,
},
},
];
export default routes;

View File

@ -1,18 +0,0 @@
import type { RouteRecordRaw } from 'vue-router';
import { EosRole } from '@vben/icons';
const routes: RouteRecordRaw[] = [
{
name: 'role',
path: '/role',
component: () => import('#/views/role/list.vue'),
meta: {
icon: EosRole,
title: '角色管理',
order: 5,
},
},
];
export default routes;

View File

@ -0,0 +1,46 @@
import type { RouteRecordRaw } from 'vue-router';
import { EosRole, IconSystem, MdiUser, RiDept } from '@vben/icons';
const routes: RouteRecordRaw[] = [
{
name: 'system',
path: '/system',
meta: {
icon: IconSystem,
title: '系统管理',
order: 4,
},
children: [
{
name: 'role',
path: '/system/role',
component: () => import('#/views/role/list.vue'),
meta: {
icon: EosRole,
title: '角色管理',
},
},
{
name: 'dept',
path: '/system/dept',
component: () => import('#/views/dept/list.vue'),
meta: {
icon: RiDept,
title: '部门管理',
},
},
{
name: 'user',
path: '/system/user',
component: () => import('#/views/user/list.vue'),
meta: {
icon: MdiUser,
title: '用户管理',
},
},
],
},
];
export default routes;

View File

@ -1,18 +0,0 @@
import type { RouteRecordRaw } from 'vue-router';
import { MdiUser } from '@vben/icons';
const routes: RouteRecordRaw[] = [
{
name: 'user',
path: '/user',
component: () => import('#/views/user/index.vue'),
meta: {
icon: MdiUser,
title: '用户管理',
order: 4,
},
},
];
export default routes;

View File

@ -58,7 +58,7 @@ export function useGridFormSchema(): VbenFormSchema[] {
{ label: $t('common.disabled'), value: 0 },
],
},
fieldName: 'status',
fieldName: 'enabled',
label: '状态',
},
{
@ -80,13 +80,13 @@ export function useColumns<T = RoleApi.Role>(
): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '角色名称',
field: 'id',
title: '角色ID',
width: 200,
},
{
field: 'id',
title: '角色ID',
field: 'name',
title: '角色名称',
width: 200,
},
{
@ -94,7 +94,7 @@ export function useColumns<T = RoleApi.Role>(
attrs: { beforeChange: onStatusChange },
name: onStatusChange ? 'CellSwitch' : 'CellTag',
},
field: 'status',
field: 'enabled',
title: '角色状态',
width: 100,
},
@ -121,7 +121,7 @@ export function useColumns<T = RoleApi.Role>(
field: 'operation',
fixed: 'right',
title: '操作',
width: 130,
width: 200,
},
];
}

View File

@ -13,7 +13,7 @@ import { Plus } from '@vben/icons';
import { Button, message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryRoleList, removeRole, updateRole } from '#/api';
import { enabledRole, queryRoleList, removeRole } from '#/api';
import { $t } from '#/locales';
import { useColumns, useGridFormSchema } from './data';
@ -28,7 +28,6 @@ const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
fieldMappingTime: [['createTime', ['startTime', 'endTime']]],
schema: useGridFormSchema(),
submitOnChange: true,
},
gridOptions: {
columns: useColumns(onActionClick, onStatusChange),
@ -37,11 +36,15 @@ const [Grid, gridApi] = useVbenVxeGrid({
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await queryRoleList({
const res = await queryRoleList({
page: page.currentPage,
pageSize: page.pageSize,
size: page.pageSize,
...formValues,
});
return {
total: res.total,
items: res.records,
};
},
},
},
@ -108,7 +111,7 @@ async function onStatusChange(newStatus: number, row: RoleApi.Role) {
`你要将${row.name}的状态切换为 【${status[newStatus.toString()]}】 吗?`,
`切换状态`,
);
await updateRole(row.id, { status: newStatus });
await enabledRole(row.id);
return true;
} catch {
return false;

View File

@ -13,15 +13,14 @@ import { IconifyIcon } from '@vben/icons';
import { Spin } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
// import { getMenuList } from '#/api';
import { createRole, updateRole } from '#/api';
import { createRole, queryMenuList, updateRole } from '#/api';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emits = defineEmits(['success']);
const formData = ref<RoleApi.SystemRole>();
const formData = ref<RoleApi.Role>();
const [Form, formApi] = useVbenForm({
schema: useFormSchema(),
@ -49,7 +48,7 @@ const [Drawer, drawerApi] = useVbenDrawer({
},
onOpenChange(isOpen) {
if (isOpen) {
const data = drawerApi.getData<RoleApi.SystemRole>();
const data = drawerApi.getData<RoleApi.Role>();
formApi.resetForm();
if (data) {
formData.value = data;
@ -59,22 +58,22 @@ const [Drawer, drawerApi] = useVbenDrawer({
id.value = undefined;
}
// if (permissions.value.length === 0) {
// loadPermissions();
// }
if (permissions.value.length === 0) {
loadPermissions();
}
}
},
});
// async function loadPermissions() {
// loadingPermissions.value = true;
// try {
// const res = await getMenuList();
// permissions.value = res as unknown as DataNode[];
// } finally {
// loadingPermissions.value = false;
// }
// }
async function loadPermissions() {
loadingPermissions.value = true;
try {
const res = await queryMenuList('all');
permissions.value = res as unknown as DataNode[];
} finally {
loadingPermissions.value = false;
}
}
const getDrawerTitle = computed(() => {
return formData.value?.id

View File

@ -1,245 +0,0 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
const props = defineProps({
prem: {
type: Object,
default: () => ({}),
},
isCreate: Boolean,
});
// const emit = defineEmits(['refresh']);
const modalTitle = computed(() => {
return props.isCreate ? '新增用户' : '编辑用户';
});
// const checkKeys = ref<number[]>([]);
const CreateRef = ref();
const open = ref<boolean>(false);
const formData = ref({
value: undefined,
code: undefined,
username: '',
nickName: '',
password: '',
phone: '',
email: '',
enabled: '',
address: '',
deptId: undefined,
roleIds: [],
permissionIds: [],
authorities: [],
});
// const formDifer = ref{};
//
const deptOptions = ref();
// const getDeptData = async () => {
// const res = await getAllDeptTree(0);
// deptOptions.value = res.data;
// };
//
const roleOptions = ref();
// const getRoleData = async () => {
// const res = await queryRoleList('');
// roleOptions.value = res.data.records.filter((item: any) => {
// return item.enabled !== false;
// });
// };
//
const handleClick = () => {
// getDeptData();
// getRoleData();
// const userId = props.prem?.id;
//
// if (!props.isCreate && userId) {
// formData.value = props.prem;
// formDifer = { ...props.prem };
// }
open.value = true;
};
//
// const diffDataForm = (newData: any, oldData: any) => {
// const result = {}; //
// Object.keys(oldData).forEach((key) => {
// if (oldData[key] !== newData[key]) {
// result[key] = newData[key];
// }
// });
// return result;
// };
//
// const handleSubmit = async () => {
// const valid = await CreateRef.value?.validate();
// if (!valid) {
// formData.value.permissionIds = checkKeys.value;
// //
// if (props.isCreate) {
// // formData.value.username = formData.value.email;
// const res = await userStore.createUser(formData.value);
// if (res.status === 200) {
// Message.success({
// content: '',
// duration: 5 * 1000,
// });
// }
// CreateRef.value?.resetFields();
// } else {
// //
// // formDifer = diffDataForm(formData.value, formDifer);
// // if (Object.keys(formDifer).length === 0) {
// // Message.success({
// // content: '',
// // duration: 3 * 1000,
// // });
// // } else {
// // formDifer.id = formData.value.id;
// // const res = await userStore.updateUser(formData.value);
// // if (res.status === 200) {
// // Message.success({
// // content: '',
// // duration: 5 * 1000,
// // });
// // }
// // }
// const res = await userStore.updateUser(formData.value);
// if (res.status === 200) {
// Message.success({
// content: '',
// duration: 5 * 1000,
// });
// }
// }
// checkKeys.value = [];
// emit('refresh');
// setVisible(false);
// }
// };
//
const handleCancel = async () => {
// checkKeys.value = [];
open.value = false;
};
</script>
<template>
<a-button
v-if="props.isCreate"
type="primary"
:style="{ marginBottom: '10px', marginLeft: '10px' }"
@click="handleClick"
>
新建
</a-button>
<a-button v-if="!props.isCreate" @click="handleClick"> 编辑 </a-button>
<a-modal width="700px" v-model:open="open" @cancel="handleCancel">
<template #title>{{ modalTitle }}</template>
<a-form ref="CreateRef" :model="formData" :style="{ width: '650px' }">
<a-form-item
field="username"
label="用户名"
:validate-trigger="['change', 'input']"
:rules="[
{ required: true, message: '用户名不能为空' },
{
match: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$/,
message: '请输入正确格式的用户名',
},
]"
>
<a-input
v-if="props.isCreate"
v-model="formData.username"
placeholder="请输入用户名"
/>
<div v-else>{{ formData.username }}</div>
</a-form-item>
<a-form-item
field="email"
label="Email"
:rules="[
{
required: true,
type: 'email',
message: 'Email不能为空',
},
]"
:validate-trigger="['change', 'input']"
>
<a-input v-model="formData.email" placeholder="请输入Email" />
</a-form-item>
<a-form-item
field="phone"
label="电话"
:rules="[
{ required: true, message: '电话不能为空' },
{ match: /^1[3-9]\d{9}$/, message: '请输入正确格式的电话' },
]"
:validate-trigger="['change', 'input']"
>
<a-input v-model="formData.phone" placeholder="请输入电话" />
</a-form-item>
<a-form-item
field="password"
label="密码"
v-if="isCreate"
:validate-trigger="['change', 'input']"
:rules="[{ required: true, message: '密码不能为空' }]"
>
<a-input v-model="formData.password" placeholder="请输入密码" />
</a-form-item>
<a-form-item field="nickName" label="昵称">
<a-input v-model="formData.nickName" placeholder="请输入昵称" />
</a-form-item>
<a-form-item field="address" label="地址">
<a-input v-model="formData.address" placeholder="请输入地址" />
</a-form-item>
<a-form-item
field="deptId"
label="部门"
:rules="[{ required: true, message: '部门不能为空' }]"
:validate-trigger="['change']"
>
<a-tree-select
v-model="formData.deptId"
:field-names="{
key: 'id',
title: 'name',
children: 'children',
}"
:data="deptOptions"
allow-clear
placeholder="请选择所属部门"
/>
</a-form-item>
<a-form-item
field="roleIds"
label="角色"
:rules="[{ required: true, message: '角色不能为空' }]"
:validate-trigger="['change']"
>
<a-select
v-model="formData.roleIds"
:options="roleOptions"
:field-names="{
value: 'id',
label: 'name',
}"
placeholder="请选择角色"
multiple
/>
</a-form-item>
</a-form>
</a-modal>
</template>

View File

@ -1,200 +0,0 @@
<script setup lang="ts">
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryUserList } from '#/api';
import UserEdit from './user-edit.vue';
// import { MOCK_TABLE_DATA } from '../table-data';
interface RowType {
id: number;
email: string;
enableState: boolean;
name: string;
phone: string;
username: string;
deptId: number;
roleId: number;
createTime: string;
ceatedBy: string;
createId: number;
}
const emit = defineEmits(['change']);
// const columns = computed(() => [
// {
// title: '',
// field: 'username',
// },
// {
// title: '',
// field: 'phone',
// },
// {
// title: '',
// field: 'email',
// },
// {
// title: '',
// field: 'name',
// },
// {
// title: '',
// field: 'address',
// },
// {
// title: '',
// field: 'enableState',
// },
// {
// title: '',
// field: 'operations',
// },
// ]);
const gridEvents: VxeGridListeners<RowType> = {
cellClick: ({ row }) => {
message.info(`cell-click: ${row.name}`);
},
};
// const props = defineProps({
// renderData: {
// type: Array,
// default: () => []
// }
// })
const gridOptions: VxeGridProps<RowType> = {
checkboxConfig: {
highlight: true,
labelField: 'name',
},
columns: [
{
title: '用户名',
field: 'username',
},
{
title: '电话',
field: 'phone',
},
],
exportConfig: {},
keepSource: true,
proxyConfig: {
ajax: {
query: async () => {
const res = await queryUserList({
page: 1,
size: 10,
});
return res.records;
},
},
},
};
const [Grid] = useVbenVxeGrid({ gridEvents, gridOptions });
const generateFormModel = () => {
return {
id: '',
name: '',
username: '',
phone: '',
email: '',
createdTime: [],
enableState: '',
deptId: '',
page: 1,
current: 1,
size: 10,
};
};
const formModel = ref(generateFormModel());
const selectUser = () => {
emit('change', {
...formModel.value,
});
};
//
const reset = () => {
formModel.value = generateFormModel();
emit('change', {
...formModel.value,
});
};
</script>
<template>
<div class="px-5">
<a-card class="general-card">
<a-row>
<a-col :flex="1">
<a-form
:model="formModel"
:label-col-props="{ span: 6 }"
:wrapper-col-props="{ span: 18 }"
label-align="right"
>
<a-row :gutter="18">
<a-col :span="6">
<a-form-item field="username" label="用户名">
<a-input
v-model:value="formModel.username"
placeholder="请输入用户名"
/>
</a-form-item>
</a-col>
<a-col :span="6">
<a-form-item field="phone" label="电话号码">
<a-input
v-model:value="formModel.phone"
placeholder="请输入电话号码"
/>
</a-form-item>
</a-col>
<a-col :span="6">
<a-form-item field="deptId" label="部门">
<a-input
v-model:value="formModel.deptId"
placeholder="所属部门"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-col>
<a-col flex="86px" style="text-align: right">
<a-space :size="18">
<a-button type="primary" @click="selectUser"> 查询 </a-button>
<a-button @click="reset"> 重置 </a-button>
</a-space>
</a-col>
</a-row>
<a-divider style="margin-top: 0" />
<a-row>
<a-col :span="12">
<a-space>
<UserEdit :is-create="true" />
</a-space>
</a-col>
</a-row>
<div class="vp-raw w-full">
<Grid />
</div>
</a-card>
</div>
</template>
<style scoped></style>

View File

@ -10,13 +10,14 @@ export default defineConfig(async () => {
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
// mock代理目标地址
target: 'http://localhost:8081/api',
// target: 'http://localhost:8081/api',
target: 'http://43.139.10.64:8082/api',
ws: true,
},
'/docx': {
changeOrigin: true,
rewrite: (path) => path.replace(/^\/docx/, ''),
target: 'http://47.112.173.8:6805/static',
target: 'http://47.112.173.8:6802/static',
},
'/pptx': {
changeOrigin: true,
@ -26,7 +27,8 @@ export default defineConfig(async () => {
'/v1': {
changeOrigin: true,
rewrite: (path) => path.replace(/^\/v1/, ''),
target: 'http://localhost:8081/v1',
// target: 'http://localhost:8081/v1',
target: 'http://43.139.10.64:8082/v1',
},
},
},

View File

@ -15,4 +15,5 @@ export const MdiUser = createIconifyIcon('mdi:user');
export const MageRobot = createIconifyIcon('mage:robot');
export const RiDept = createIconifyIcon('ri:door-open-line');
export const EosRole = createIconifyIcon('eos-icons:role-binding-outlined');
export const IconSystem = createIconifyIcon('icon-park-twotone:system');
// export const MdiUser = createIconifyIcon('mdi:user');