frontend: MenuFormModal 增加菜单图标选择和层级展示优化

This commit is contained in:
小蟑螂
2026-05-04 02:38:08 +08:00
parent eefe9244cb
commit 143cf1b977
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { MenuVO } from '#/api/system/menu/types';
import type { PermissionVO } from '#/api/system/permission/types';
import { ref } from 'vue';
@@ -7,13 +8,13 @@ import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
import {
Cascader,
Form,
Input,
InputNumber,
message,
Popover,
Radio,
Select,
Switch,
} from 'ant-design-vue';
@@ -27,7 +28,7 @@ import {
addMenuPermissionApi,
removeMenuPermissionApi,
} from '#/api/system/menu-permission';
import { getAllPermissionsApi } from '#/api/system/permission';
import { getPermissionTreeApi } from '#/api/system/permission';
import IconSelector from './IconSelector.vue';
@@ -94,52 +95,234 @@ const formData = ref<FormData>({
keepAlive: false,
});
// 下拉选项数据
const parentMenuOptions = ref<{ label: string; value: number }[]>([]);
const permissionOptions = ref<{ label: string; value: number }[]>([]);
interface MenuCascaderOption {
value: number;
label: string;
disabled?: boolean;
children?: MenuCascaderOption[];
}
/** 父菜单级联选项(树) */
const parentMenuTreeOptions = ref<MenuCascaderOption[]>([]);
/** 级联选中路径,与 formData.parentId(末级 id)同步 */
const parentMenuPath = ref<number[]>([]);
/** 权限树(级联多选) */
const permissionTreeOptions = ref<MenuCascaderOption[]>([]);
/** 多选级联:每项为从根到选中节点的一条路径 */
const permissionPaths = ref<number[][]>([]);
const selectedPermissions = ref<number[]>([]);
const originalPermissions = ref<number[]>([]);
/** 无图标时占位,点击仍打开选择器 */
const GridIcon = createIconifyIcon('lucide:grid-3x3');
// 获取父菜单选项
/** 编辑中不能选自己及子孙为父 */
function collectExcludedMenuIdsForParent(
flat: MenuVO.MenuInfo[],
editingId?: number,
): Set<number> {
if (editingId == null) {
return new Set();
}
const excluded = new Set<number>([editingId]);
const childrenByParent = new Map<number, number[]>();
for (const m of flat) {
const p = m.parentId;
if (p == null || p === undefined || Number(p) === 0) {
continue;
}
const pk = Number(p);
if (!childrenByParent.has(pk)) {
childrenByParent.set(pk, []);
}
childrenByParent.get(pk)!.push(m.id);
}
const stack = [...(childrenByParent.get(editingId) || [])];
while (stack.length) {
const id = stack.pop()!;
if (excluded.has(id)) {
continue;
}
excluded.add(id);
stack.push(...(childrenByParent.get(id) || []));
}
return excluded;
}
function buildMenuCascaderOptions(
flat: MenuVO.MenuInfo[],
excludeIds: Set<number>,
): MenuCascaderOption[] {
const visible = flat.filter((m) => !excludeIds.has(m.id));
const visibleIds = new Set(visible.map((m) => m.id));
type BuildNode = { menu: MenuVO.MenuInfo; children: BuildNode[] };
const nodeById = new Map<number, BuildNode>();
for (const m of visible) {
nodeById.set(m.id, { menu: m, children: [] });
}
const roots: BuildNode[] = [];
for (const m of visible) {
const node = nodeById.get(m.id)!;
const p = m.parentId;
const hasValidParent =
p != null && p !== undefined && Number(p) !== 0 && visibleIds.has(Number(p));
if (hasValidParent) {
nodeById.get(Number(p))!.children.push(node);
} else {
roots.push(node);
}
}
const sortNodes = (arr: BuildNode[]) =>
arr.sort((a, b) => (a.menu.order ?? 0) - (b.menu.order ?? 0));
function toOptions(nodes: BuildNode[]): MenuCascaderOption[] {
sortNodes(nodes);
return nodes.map(({ menu, children }) => {
sortNodes(children);
const sub = toOptions(children);
return {
value: menu.id,
label: menu.title || menu.name,
children: sub.length ? sub : undefined,
};
});
}
sortNodes(roots);
return toOptions(roots);
}
function findMenuPathById(
options: MenuCascaderOption[],
menuId: number,
currentPath: number[] = [],
): null | number[] {
for (const option of options) {
const nextPath = [...currentPath, option.value];
if (option.value === menuId) {
return nextPath;
}
if (option.children?.length) {
const found = findMenuPathById(option.children, menuId, nextPath);
if (found) {
return found;
}
}
}
return null;
}
function syncParentMenuPath() {
const pid = formData.value.parentId;
if (pid == null || pid === undefined) {
parentMenuPath.value = [];
return;
}
const path = findMenuPathById(parentMenuTreeOptions.value, Number(pid));
parentMenuPath.value = path ?? [];
}
function onParentMenuCascaderChange(value: unknown) {
const arr = Array.isArray(value)
? (value as unknown[])
.map((v) => Number(v))
.filter((n) => Number.isFinite(n) && n > 0)
: [];
parentMenuPath.value = arr;
formData.value.parentId = arr.length ? arr[arr.length - 1] : undefined;
}
// 获取父菜单选项(扁平列表建树,供级联)
async function fetchParentMenuOptions() {
try {
const data = await getAllMenusApi();
const options: Array<{ label: string; value: number }> = [];
const addMenuOptions = (menus: MenuVO.MenuInfo[], level = 0) => {
menus.forEach((menu) => {
const prefix = ' '.repeat(level);
options.push({
label: `${prefix}${menu.title || menu.name}`,
value: menu.id,
});
if (menu.children && menu.children.length > 0) {
addMenuOptions(menu.children, level + 1);
}
});
};
addMenuOptions(data);
parentMenuOptions.value = options;
const editingId = isEdit.value ? currentRecord.value?.id : undefined;
const exclude = collectExcludedMenuIdsForParent(data, editingId);
parentMenuTreeOptions.value = buildMenuCascaderOptions(data, exclude);
syncParentMenuPath();
} catch (error) {
console.error('获取菜单列表失败:', error);
parentMenuTreeOptions.value = [];
parentMenuPath.value = [];
}
}
// 获取权限选项
function mapPermissionTreeToCascaderOptions(
nodes: PermissionVO.PermissionInfoVO[] | undefined,
): MenuCascaderOption[] {
if (!nodes?.length) {
return [];
}
return [...nodes]
.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
.map((p) => {
const children = mapPermissionTreeToCascaderOptions(p.children);
return {
value: p.id,
label: p.name,
disabled: p.status !== 1,
children: children.length ? children : undefined,
};
});
}
function syncSelectedPermissionsFromPaths() {
const ids = new Set<number>();
for (const path of permissionPaths.value) {
if (path.length) {
ids.add(path[path.length - 1]!);
}
}
selectedPermissions.value = [...ids];
}
function syncPermissionPathsFromIds() {
const opts = permissionTreeOptions.value;
const ids = selectedPermissions.value;
if (!opts.length || !ids.length) {
permissionPaths.value = [];
return;
}
const paths: number[][] = [];
for (const id of ids) {
const path = findMenuPathById(opts, id);
if (path?.length) {
paths.push(path);
}
}
permissionPaths.value = paths;
}
function coerceMultipleCascaderPaths(val: unknown): number[][] {
if (!Array.isArray(val)) {
return [];
}
return (val as unknown[])
.map((item) => {
if (!Array.isArray(item)) {
return [];
}
return item
.map((x) => Number(x))
.filter((n) => Number.isFinite(n) && n > 0);
})
.filter((p) => p.length > 0);
}
function onPermissionPathsUpdate(val: unknown) {
permissionPaths.value = coerceMultipleCascaderPaths(val);
syncSelectedPermissionsFromPaths();
}
// 获取权限选项(树形接口 → 级联多选)
async function fetchPermissionOptions() {
try {
const data = await getAllPermissionsApi();
const options = data.map((permission) => ({
label: permission.name,
value: permission.id,
}));
permissionOptions.value = options;
const data = await getPermissionTreeApi();
permissionTreeOptions.value = mapPermissionTreeToCascaderOptions(data);
syncPermissionPathsFromIds();
} catch (error) {
console.error('获取权限列表失败:', error);
console.error('获取权限树失败:', error);
permissionTreeOptions.value = [];
permissionPaths.value = [];
}
}
@@ -228,6 +411,10 @@ function open(edit: boolean, record?: MenuVO.MenuInfo) {
function close() {
modalApi.close();
formRef.value?.resetFields();
parentMenuPath.value = [];
parentMenuTreeOptions.value = [];
permissionPaths.value = [];
permissionTreeOptions.value = [];
selectedPermissions.value = [];
originalPermissions.value = [];
emit('cancel');
@@ -371,23 +558,41 @@ defineExpose({
</Form.Item>
<Form.Item label="父菜单" name="parentId">
<Select
v-model:value="formData.parentId"
placeholder="请选择父菜单"
:options="parentMenuOptions"
<Cascader
:value="parentMenuPath"
:options="parentMenuTreeOptions"
allow-clear
change-on-select
class="w-full"
expand-trigger="hover"
placeholder="请选择父菜单(任意层级可选)"
:field-names="{
label: 'label',
value: 'value',
children: 'children',
}"
@change="onParentMenuCascaderChange"
/>
</Form.Item>
<Form.Item label="权限列表" name="permissions">
<Select
v-model:value="selectedPermissions"
mode="multiple"
placeholder="请选择权限"
:options="permissionOptions"
<Cascader
:value="permissionPaths"
:options="permissionTreeOptions"
allow-clear
change-on-select
class="w-full"
:max-tag-count="3"
:max-tag-text-length="10"
expand-trigger="hover"
max-tag-count="responsive"
multiple
placeholder="请选择权限(任意层级可选,可多选)"
show-search
:field-names="{
label: 'label',
value: 'value',
children: 'children',
}"
@update:value="onPermissionPathsUpdate"
/>
</Form.Item>