refactor: 调整页面组件位置

This commit is contained in:
2026-08-14 14:37:54 +08:00
parent 5f824531ce
commit c51e13f4b4
82 changed files with 1 additions and 1 deletions
@@ -0,0 +1,429 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { useDebounceFn } from '@vueuse/core';
import { Input, Select, Spin } from 'ant-design-vue';
interface Props {
modelValue?: string;
}
interface Emits {
(e: 'update:modelValue', value: string): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const ICONIFY = 'https://api.iconify.design';
const GLOBAL_PREFIX = '__global__';
/** 常用图标集(Iconify prefix),可继续扩充 */
const COLLECTION_OPTIONS = [
{
label: '全局搜索(不限图标集,仅关键词)',
value: GLOBAL_PREFIX,
},
{ label: 'Lucide', value: 'lucide' },
{ label: 'Material Design Icons', value: 'mdi' },
{ label: 'Carbon', value: 'carbon' },
{ label: 'Tabler', value: 'tabler' },
{ label: 'Phosphor', value: 'ph' },
{ label: 'Remix Icon', value: 'ri' },
{ label: 'Heroicons', value: 'heroicons' },
{ label: 'Material Symbols', value: 'material-symbols' },
{ label: 'Ant Design Icons', value: 'ant-design' },
{ label: 'Bootstrap Icons', value: 'bi' },
{ label: 'MingCute', value: 'mingcute' },
{ label: 'Logos', value: 'logos' },
{ label: 'Simple Icons', value: 'simple-icons' },
{ label: 'Font Awesome 6', value: 'fa6-solid' },
{ label: 'Iconoir', value: 'iconoir' },
];
const searchKeyword = ref('');
const selectedCollection = ref('lucide');
const selectedIcon = ref(props.modelValue || '');
const currentPage = ref(1);
const pageSize = 36;
const browseFlat = ref<string[]>([]);
const searchResultIcons = ref<string[]>([]);
const loading = ref(false);
const loadError = ref('');
const collectionCache = new Map<string, string[]>();
function flattenCollectionBody(
prefix: string,
data: {
uncategorized?: string[];
categories?: Record<string, string[]>;
},
): string[] {
const set = new Set<string>();
for (const n of data.uncategorized || []) {
set.add(`${prefix}:${n}`);
}
if (data.categories) {
for (const arr of Object.values(data.categories)) {
for (const n of arr) {
set.add(`${prefix}:${n}`);
}
}
}
return [...set].sort((a, b) => a.localeCompare(b));
}
async function fetchCollectionIcons(prefix: string): Promise<string[]> {
const hit = collectionCache.get(prefix);
if (hit) {
return hit;
}
const res = await fetch(
`${ICONIFY}/collection?prefix=${encodeURIComponent(prefix)}`,
);
if (!res.ok) {
throw new Error(`Iconify collection ${res.status}`);
}
const data = await res.json();
const list = flattenCollectionBody(prefix, data);
collectionCache.set(prefix, list);
return list;
}
const isGlobalMode = computed(
() => selectedCollection.value === GLOBAL_PREFIX,
);
async function refreshIcons() {
const q = searchKeyword.value.trim();
const prefix = selectedCollection.value;
loading.value = true;
loadError.value = '';
try {
if (q) {
let url = `${ICONIFY}/search?query=${encodeURIComponent(q)}&limit=400`;
if (!isGlobalMode.value) {
url += `&prefix=${encodeURIComponent(prefix)}`;
}
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Iconify search ${res.status}`);
}
const data = await res.json();
searchResultIcons.value = Array.isArray(data.icons) ? data.icons : [];
} else {
searchResultIcons.value = [];
if (isGlobalMode.value) {
browseFlat.value = [];
} else {
browseFlat.value = await fetchCollectionIcons(prefix);
}
}
} catch (e: unknown) {
loadError.value = e instanceof Error ? e.message : '加载失败';
browseFlat.value = [];
searchResultIcons.value = [];
} finally {
loading.value = false;
}
}
const debouncedRefresh = useDebounceFn(refreshIcons, 320);
const activeSource = computed(() => {
return searchKeyword.value.trim()
? searchResultIcons.value
: browseFlat.value;
});
const displayedIconNames = computed(() => {
const source = activeSource.value;
const start = (currentPage.value - 1) * pageSize;
return source.slice(start, start + pageSize);
});
const totalPages = computed(() => {
const n = activeSource.value.length;
return Math.max(1, Math.ceil(n / pageSize));
});
const visiblePages = computed(() => {
const pages: number[] = [];
const total = totalPages.value;
const current = currentPage.value;
if (total <= 7) {
for (let i = 1; i <= total; i++) {
pages.push(i);
}
} else if (current <= 4) {
for (let i = 1; i <= 5; i++) {
pages.push(i);
}
} else if (current >= total - 3) {
for (let i = total - 4; i <= total; i++) {
pages.push(i);
}
} else {
for (let i = current - 2; i <= current + 2; i++) {
pages.push(i);
}
}
return pages;
});
const showEllipsis = computed(() => {
return (
totalPages.value > 7 &&
currentPage.value > 4 &&
currentPage.value < totalPages.value - 3
);
});
const selectIcon = (iconName: string) => {
selectedIcon.value = iconName;
emit('update:modelValue', iconName);
};
const goToPage = (page: number) => {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page;
}
};
watch(
() => props.modelValue,
(newVal) => {
selectedIcon.value = newVal || '';
},
);
watch(selectedCollection, () => {
currentPage.value = 1;
debouncedRefresh();
});
watch(searchKeyword, () => {
currentPage.value = 1;
debouncedRefresh();
});
onMounted(() => {
void refreshIcons();
});
</script>
<template>
<div class="icon-selector">
<div class="mb-2 flex flex-col gap-2 px-2">
<Select
v-model:value="selectedCollection"
:options="COLLECTION_OPTIONS"
class="w-full"
placeholder="图标集"
/>
<Input
v-model:value="searchKeyword"
placeholder="搜索图标(留空则浏览当前图标集)"
allow-clear
/>
</div>
<Spin :spinning="loading">
<div
v-if="loadError"
class="text-destructive px-2 py-4 text-center text-sm"
>
{{ loadError }}
</div>
<div
v-else-if="
!searchKeyword.trim() &&
isGlobalMode &&
displayedIconNames.length === 0
"
class="text-muted-foreground px-2 py-8 text-center text-sm"
>
「全局搜索」模式下请在上框输入关键词;或切换到具体图标集以分页浏览。
</div>
<div
v-else
class="grid max-h-[360px] w-full grid-cols-6 justify-items-center overflow-y-auto"
>
<button
v-for="name in displayedIconNames"
:key="name"
type="button"
class="focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground text-foreground/80 inline-flex h-8 w-8 items-center justify-center whitespace-nowrap rounded-full px-1 text-lg font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:class="{
'bg-primary text-primary-foreground': selectedIcon === name,
}"
:title="name"
@click="selectIcon(name)"
>
<IconifyIcon :icon="name" class="size-4" />
</button>
</div>
</Spin>
<div
class="flex-center flex justify-end overflow-hidden border-t py-2 pr-3"
>
<nav size="small">
<div class="flex w-full items-center gap-1">
<button
type="button"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === 1"
@click="goToPage(1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevrons-left size-4"
>
<path d="m11 17-5-5 5-5" />
<path d="m18 17-5-5 5-5" />
</svg>
</button>
<button
type="button"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === 1"
@click="goToPage(currentPage - 1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevron-left size-4"
>
<path d="m15 18-6-6 6-6" />
</svg>
</button>
<template v-for="page in visiblePages" :key="page">
<button
type="button"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-xs font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:class="{
'bg-primary text-primary-foreground': currentPage === page,
}"
@click="goToPage(page)"
>
{{ page }}
</button>
</template>
<div
v-if="showEllipsis"
class="flex size-5 items-center justify-center"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-ellipsis size-4"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>
</div>
<button
type="button"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === totalPages"
@click="goToPage(currentPage + 1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevron-right size-4"
>
<path d="m9 18 6-6-6-6" />
</svg>
</button>
<button
type="button"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === totalPages"
@click="goToPage(totalPages)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevrons-right size-4"
>
<path d="m6 17 5-5-5-5" />
<path d="m13 17 5-5-5-5" />
</svg>
</button>
</div>
</nav>
</div>
</div>
</template>
<style scoped>
.icon-selector {
width: 100%;
max-width: 400px;
}
button {
transition: all 0.2s ease;
}
button:hover {
transform: scale(1.1);
}
button:active {
transform: scale(0.95);
}
</style>
@@ -0,0 +1,709 @@
<script setup lang="ts">
import type { MenuVO } from '#/api/system/menu/types';
import type { PermissionVO } from '#/api/system/permission/types';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
import {
Cascader,
Form,
Input,
InputNumber,
message,
Popover,
Radio,
Switch,
} from 'ant-design-vue';
import {
createMenuApi,
getAllMenusApi,
getMenuDetailApi,
updateMenuApi,
} from '#/api/system/menu';
import {
addMenuPermissionApi,
removeMenuPermissionApi,
} from '#/api/system/menu-permission';
import { getPermissionTreeApi } from '#/api/system/permission';
import IconSelector from './IconSelector.vue';
type MenuFormSuccessPayload =
| { mode: 'update'; menu: MenuVO.MenuInfo }
| { mode: 'create' };
const emit = defineEmits<{
cancel: [];
success: [payload?: MenuFormSuccessPayload];
}>();
// 创建Vben Modal实例
const [Modal, modalApi] = useVbenModal({
title: '菜单管理',
draggable: true, // 开启拖拽
contentClass: 'px-6 py-4', // 使用Tailwind CSS设置内边距
onConfirm: handleSubmit,
onCancel: close,
onOpenChange: (isOpen: boolean) => {
if (isOpen) {
fetchParentMenuOptions();
fetchPermissionOptions();
}
},
});
// 响应式数据
const isEdit = ref(false);
const currentRecord = ref<MenuVO.MenuInfo | null>(null);
const formRef = ref();
// 内部表单数据类型
interface FormData {
parentId?: number;
superMenu: boolean;
name: string;
title: string;
path: string;
component: string;
redirect: string;
icon: string;
order: number;
type: string;
visible: boolean;
status: boolean;
keepAlive: boolean;
}
// 表单数据
const formData = ref<FormData>({
parentId: undefined,
superMenu: false,
name: '',
title: '',
path: '',
component: '',
redirect: '',
icon: '',
order: 0,
type: 'menu',
visible: true,
status: true,
keepAlive: false,
});
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 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 getPermissionTreeApi();
permissionTreeOptions.value = mapPermissionTreeToCascaderOptions(data);
syncPermissionPathsFromIds();
} catch (error) {
console.error('获取权限树失败:', error);
permissionTreeOptions.value = [];
permissionPaths.value = [];
}
}
// 打开模态框
function open(edit: boolean, record?: MenuVO.MenuInfo) {
isEdit.value = edit;
currentRecord.value = record || null;
// 更新模态框标题
modalApi.setState({
title: edit ? '编辑菜单' : '添加菜单',
});
modalApi.open();
if (edit && record) {
// 编辑模式,填充表单数据
formData.value = {
parentId: record.parentId || undefined,
superMenu: record.superMenu === 1, // 转换为boolean
name: record.name,
title: record.title || '',
path: record.path || '',
component: record.component || '',
redirect: record.redirect || '',
icon: record.icon || '',
order: record.order || 0,
type: record.type,
visible: record.visible === 1, // 转换为boolean
status: record.status === 1, // 转换为boolean
keepAlive: record.keepAlive === 1, // 转换为boolean
};
// 设置权限数据
if ((record as any).permissions && (record as any).permissions.length > 0) {
selectedPermissions.value = (record as any).permissions.map(
(p: any) => p.id,
);
originalPermissions.value = [...selectedPermissions.value];
} else {
selectedPermissions.value = [];
originalPermissions.value = [];
}
} else if (!edit && record) {
// 添加下级菜单模式,自动选中父菜单
formData.value = {
parentId: record.id, // 自动设置为当前菜单的ID作为父菜单
superMenu: false,
name: '',
title: '',
path: '',
component: '',
redirect: '',
icon: '',
order: 0,
type: 'menu',
visible: true,
status: true,
keepAlive: false,
};
} else {
// 新增根菜单模式,重置表单
formData.value = {
parentId: undefined,
superMenu: false,
name: '',
title: '',
path: '',
component: '',
redirect: '',
icon: '',
order: 0,
type: 'menu',
visible: true,
status: true,
keepAlive: false,
};
// 重置权限数据
selectedPermissions.value = [];
originalPermissions.value = [];
}
}
// 关闭模态框
function close() {
modalApi.close();
formRef.value?.resetFields();
parentMenuPath.value = [];
parentMenuTreeOptions.value = [];
permissionPaths.value = [];
permissionTreeOptions.value = [];
selectedPermissions.value = [];
originalPermissions.value = [];
emit('cancel');
}
// 处理权限变更
async function handlePermissionChange() {
if (!currentRecord.value) return;
const menuId = currentRecord.value.id;
const currentPermissions = selectedPermissions.value;
const originalPermissionsList = originalPermissions.value;
// 找出新增的权限
const addedPermissions = currentPermissions.filter(
(id) => !originalPermissionsList.includes(id),
);
// 找出移除的权限
const removedPermissions = originalPermissionsList.filter(
(id) => !currentPermissions.includes(id),
);
try {
// 添加新权限
for (const permissionId of addedPermissions) {
await addMenuPermissionApi({
menuId,
permissionId,
});
}
// 移除权限
for (const permissionId of removedPermissions) {
await removeMenuPermissionApi({
menuId,
permissionId,
});
}
// 更新原始权限列表
originalPermissions.value = [...currentPermissions];
if (addedPermissions.length > 0 || removedPermissions.length > 0) {
message.success('权限更新成功');
}
} catch (error) {
console.error('权限更新失败:', error);
message.error('权限更新失败');
}
}
// 提交表单
async function handleSubmit() {
try {
await formRef.value?.validate();
// 设置模态框为loading状态
modalApi.setState({ confirmLoading: true });
// 转换boolean值为number值
const submitData = {
...formData.value,
superMenu: formData.value.superMenu ? 1 : 0,
visible: formData.value.visible ? 1 : 0,
status: formData.value.status ? 1 : 0,
keepAlive: formData.value.keepAlive ? 1 : 0,
};
if (isEdit.value && currentRecord.value) {
const menuId = currentRecord.value.id;
await updateMenuApi(menuId, submitData);
message.success('更新菜单成功');
// 处理权限变更
await handlePermissionChange();
// 详情含最新权限,供列表行就地合并,避免整表 reload 导致树折叠
const menu = await getMenuDetailApi(menuId);
emit('success', { mode: 'update', menu });
close();
return;
}
// 创建菜单(结构变化多,仍整表刷新)
const newMenu = await createMenuApi(submitData);
message.success('创建菜单成功');
if (selectedPermissions.value.length > 0 && newMenu?.id) {
for (const permissionId of selectedPermissions.value) {
await addMenuPermissionApi({
menuId: newMenu.id,
permissionId,
});
}
message.success('权限分配成功');
}
emit('success', { mode: 'create' });
close();
} catch (error) {
console.error('提交菜单失败:', error);
message.error('提交菜单失败');
} finally {
modalApi.setState({ confirmLoading: false });
}
}
// 暴露方法
defineExpose({
open,
close,
});
</script>
<template>
<Modal>
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
class="space-y-5"
>
<Form.Item
label="菜单类型"
name="type"
:rules="[{ required: true, message: '请选择菜单类型' }]"
>
<Radio.Group
v-model:value="formData.type"
button-style="solid"
class="w-full"
>
<Radio.Button value="catalog" class="flex-1">目录</Radio.Button>
<Radio.Button value="menu" class="flex-1">菜单</Radio.Button>
<Radio.Button value="button" class="flex-1">按钮</Radio.Button>
<Radio.Button value="embedded" class="flex-1">内联</Radio.Button>
<Radio.Button value="link" class="flex-1">外链</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item label="父菜单" name="parentId">
<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">
<Cascader
:value="permissionPaths"
:options="permissionTreeOptions"
allow-clear
change-on-select
class="w-full"
expand-trigger="hover"
max-tag-count="responsive"
multiple
placeholder="请选择权限(任意层级可选,可多选)"
show-search
:field-names="{
label: 'label',
value: 'value',
children: 'children',
}"
@update:value="onPermissionPathsUpdate"
/>
</Form.Item>
<Form.Item
label="菜单名称"
name="name"
:rules="[{ required: true, message: '请输入菜单名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入菜单名称" />
</Form.Item>
<Form.Item label="菜单标题" name="title">
<Input v-model:value="formData.title" placeholder="请输入菜单标题" />
</Form.Item>
<Form.Item label="路由路径" name="path">
<Input v-model:value="formData.path" placeholder="请输入路由路径" />
</Form.Item>
<Form.Item label="页面组件" name="component">
<Input
v-model:value="formData.component"
placeholder="请输入页面组件"
/>
</Form.Item>
<Form.Item label="重定向地址" name="redirect">
<Input
v-model:value="formData.redirect"
placeholder="请输入重定向地址"
/>
</Form.Item>
<!-- 外层只负责标签;name 仅绑在触发 Input 上,避免 Popover 浮层内控件被同一 Form.Item 收集导致 FormItemContext 刷屏 -->
<Form.Item label="路由图标">
<Popover
placement="bottomRight"
trigger="click"
overlay-class-name="icon-selector-popover"
>
<template #content>
<IconSelector v-model="formData.icon" />
</template>
<!-- Popover Trigger 需要落在真实 DOM 上;no-style 的 Form.Item 常无包裹节点,会导致点击无响应 -->
<div class="w-full">
<Form.Item name="icon" no-style>
<Input
v-model:value="formData.icon"
placeholder="点击选择或查看 Iconify 图标名"
readonly
style="cursor: pointer"
>
<template #prefix>
<span class="inline-flex items-center pr-1">
<IconifyIcon
v-if="formData.icon"
:icon="formData.icon"
class="size-4 shrink-0 text-foreground"
/>
<GridIcon v-else class="size-4 shrink-0 opacity-40" />
</span>
</template>
</Input>
</Form.Item>
</div>
</Popover>
</Form.Item>
<Form.Item label="排序" name="order">
<InputNumber
v-model:value="formData.order"
placeholder="请输入排序"
:min="0"
/>
</Form.Item>
<Form.Item label="是否显示" name="visible">
<Switch
v-model:checked="formData.visible"
checked-children="显示"
un-checked-children="隐藏"
class="w-12"
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
checked-children="启用"
un-checked-children="禁用"
class="w-12"
/>
</Form.Item>
<Form.Item label="是否缓存" name="keepAlive">
<Switch
v-model:checked="formData.keepAlive"
checked-children="缓存"
un-checked-children="不缓存"
class="w-12"
/>
</Form.Item>
<Form.Item label="超级菜单" name="superMenu">
<Switch
v-model:checked="formData.superMenu"
checked-children="是"
un-checked-children="否"
class="w-12"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,473 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MenuVO } from '#/api/system/menu/types';
import { onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
batchSortMenuApi,
deleteMenuApi,
getAllMenusApi,
} from '#/api/system/menu';
import MenuFormModal from './components/MenuFormModal.vue';
defineOptions({ name: 'MenuManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
const PlusCircleIcon = createIconifyIcon('lucide:plus-circle');
const ExpandIcon = createIconifyIcon('lucide:chevrons-down');
const CollapseIcon = createIconifyIcon('lucide:chevrons-up');
// 响应式数据
const loading = ref(false);
const menuFormModalRef = ref();
/** 与 proxy query 返回的 `items` 同一数组引用,用于就地更新行,避免依赖 getTableData 结构差异导致误判走 reload */
const lastMenuFlatItems = ref<MenuVO.MenuInfo[]>([]);
function normalizeMenuParentId(v: unknown): number | null {
if (v === null || v === undefined) {
return null;
}
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : null;
}
function sameMenuParent(a: unknown, b: unknown) {
return normalizeMenuParentId(a) === normalizeMenuParentId(b);
}
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 60,
title: '序号',
},
{
field: 'name',
title: '菜单名称',
minWidth: 200,
showOverflow: 'tooltip' as const,
treeNode: true, // 启用树节点显示
dragSort: true, // 启用拖拽排序
// 移除自定义插槽,让拖拽控件正常显示
},
{
field: 'title',
title: '菜单标题',
minWidth: 150,
showOverflow: 'tooltip' as const,
},
{
field: 'icon',
title: '图标',
width: 72,
align: 'center' as const,
slots: { default: 'icon' },
},
{
field: 'path',
title: '路由路径',
minWidth: 200,
showOverflow: 'tooltip' as const,
},
{
field: 'component',
title: '页面组件',
minWidth: 180,
showOverflow: 'tooltip' as const,
},
{
title: '权限列表',
minWidth: 200,
slots: { default: 'permissions' },
},
{
title: '类型',
minWidth: 100,
slots: { default: 'menuType' },
},
{
title: '状态',
minWidth: 100,
slots: { default: 'menuStatus' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
title: '操作',
minWidth: 280,
fixed: 'right' as const,
showOverflow: false,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: {
isHover: true,
drag: true, // 启用行拖拽
height: 52,
},
showOverflow: true,
size: 'small',
rowDragConfig: {
isPeerDrag: true, // 启用同层级拖拽限制
},
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
export: true, // 启用导出功能
},
data: [],
treeConfig: {
transform: true,
rowField: 'id',
parentField: 'parentId',
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const data = await getAllMenusApi();
lastMenuFlatItems.value = data;
// 直接返回扁平化数据,让 vxe-table 自动构建树形结构
return {
items: data,
total: data.length,
};
} catch (error) {
console.error('获取菜单列表失败:', error);
message.error('获取菜单列表失败');
lastMenuFlatItems.value = [];
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
function getGridMenuFlatFallback(): MenuVO.MenuInfo[] {
const grid = gridApi?.grid as any;
if (!grid?.getTableData) {
return [];
}
const td = grid.getTableData();
return (td?.fullData ?? td?.tableData ?? []) as MenuVO.MenuInfo[];
}
/** 就地合并更新后的菜单行,保持树展开状态;父级变更时需整表重建树结构 */
function patchMenuRowFromServer(menu: MenuVO.MenuInfo) {
if (!menu?.id) {
refreshTable();
return;
}
const idNum = Number(menu.id);
const list =
lastMenuFlatItems.value.length > 0
? lastMenuFlatItems.value
: getGridMenuFlatFallback();
const row = list.find((r) => Number(r.id) === idNum);
if (!row) {
refreshTable();
return;
}
if (!sameMenuParent(row.parentId, menu.parentId)) {
refreshTable();
return;
}
Object.assign(row, menu);
row.permissions = menu.permissions ? [...menu.permissions] : [];
}
// 处理添加菜单
function handleAdd() {
menuFormModalRef.value?.open(false);
}
// 处理添加下级菜单
function handleAddChild(record: MenuVO.MenuInfo) {
menuFormModalRef.value?.open(false, record);
}
// 处理编辑菜单
function handleEdit(record: MenuVO.MenuInfo) {
menuFormModalRef.value?.open(true, record);
}
// 处理删除菜单
async function handleDelete(record: MenuVO.MenuInfo) {
try {
await deleteMenuApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除菜单失败:', error);
message.error('删除菜单失败');
}
}
// 处理模态框成功:更新菜单只合并当前行;新建仍整表刷新
function handleModalSuccess(
payload?: { mode: 'update'; menu: MenuVO.MenuInfo } | { mode: 'create' },
) {
if (payload?.mode === 'update' && payload.menu) {
patchMenuRowFromServer(payload.menu);
return;
}
refreshTable();
}
// 防重复调用标志
let isUpdating = false;
// 处理拖拽排序
const handleDragSort = async (_params: any) => {
// 防止重复调用
if (isUpdating) {
return;
}
try {
isUpdating = true;
// 获取当前表格数据
const tableDataResult = gridApi.grid.getTableData();
const tableData = tableDataResult?.tableData || [];
// 构建排序数据
const sortItems = tableData.map((item: MenuVO.MenuInfo, index: number) => ({
menuId: item.id,
order: index + 1, // 排序值从1开始
}));
// 调用排序接口
await batchSortMenuApi({ sortItems });
// 排序成功后不需要重新加载数据,因为表格数据已经更新
} catch (error: any) {
console.error('拖拽排序失败:', error);
if (error?.message) {
message.error(error.message);
} else {
message.error('排序更新失败');
}
// 排序失败时重新加载数据,恢复原始状态
gridApi.reload();
} finally {
isUpdating = false;
}
};
// 全部展开树形表格
function expandAllTree() {
if (gridApi) {
const vxeTable = (gridApi as any).grid;
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
vxeTable.setAllTreeExpand(true);
}
}
}
// 全部收起树形表格
function collapseAllTree() {
if (gridApi) {
const vxeTable = (gridApi as any).grid;
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
vxeTable.setAllTreeExpand(false);
}
}
}
// 获取菜单类型标签
function getMenuTypeLabel(type: string) {
const typeMap: Record<string, string> = {
catalog: '目录',
menu: '菜单',
button: '按钮',
embedded: '内联',
link: '外链',
};
return typeMap[type] || type;
}
// 获取菜单类型颜色
function getMenuTypeColor(type: string) {
const colorMap: Record<string, string> = {
catalog: 'blue',
menu: 'green',
button: 'orange',
embedded: 'purple',
link: 'cyan',
};
return colorMap[type] || 'default';
}
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '菜单管理',
gridEvents: {
// 拖拽排序事件
rowDragend: handleDragSort,
} as any,
});
// 添加Grid组件的ref
const gridRef = ref();
// 在组件挂载后绑定拖拽事件
onMounted(() => {
// 延迟绑定,确保Grid组件完全初始化
setTimeout(() => {
if (gridRef.value) {
// 尝试直接绑定VxeTable的拖拽事件
const vxeGrid = gridRef.value;
if (vxeGrid && vxeGrid.$refs && vxeGrid.$refs.grid) {
const grid = vxeGrid.$refs.grid;
// 绑定拖拽事件
grid.on('row-drag-end', (params: any) => {
handleDragSort(params);
});
}
}
}, 1000);
});
</script>
<template>
<Page title="菜单管理" auto-content-height>
<!-- VbenVxeGrid 表格 -->
<Grid ref="gridRef" :loading="loading" class="menu-grid">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加菜单
</Button>
<Button @click="expandAllTree">
<ExpandIcon />
全部展开
</Button>
<Button @click="collapseAllTree">
<CollapseIcon />
全部收起
</Button>
<div class="text-sm text-gray-500">
💡 提示:可直接拖拽菜单名称列进行排序
</div>
</Space>
</template>
<!-- 菜单名称列 - 移除自定义插槽以支持拖拽控件正常显示 -->
<!-- 图标列 -->
<template #icon="{ row }: { row: MenuVO.MenuInfo }">
<div
v-if="row.icon"
class="flex items-center justify-center"
:title="row.icon"
>
<IconifyIcon :icon="row.icon" class="size-4 text-blue-600" />
</div>
<span v-else class="text-gray-400">-</span>
</template>
<!-- 菜单类型列 -->
<template #menuType="{ row }: { row: any }">
<Tag :color="getMenuTypeColor(row.type)">
{{ getMenuTypeLabel(row.type) }}
</Tag>
</template>
<!-- 菜单状态列 -->
<template #menuStatus="{ row }: { row: any }">
<Tag :color="row.status === 1 ? 'green' : 'red'">
{{ row.status === 1 ? '启用' : '禁用' }}
</Tag>
</template>
<!-- 权限名称列 -->
<template #permissions="{ row }: { row: any }">
<div
v-if="row.permissions && row.permissions.length > 0"
class="flex flex-wrap gap-1"
>
<Tag
v-for="permission in row.permissions"
:key="permission.id"
:color="permission.status === 1 ? 'blue' : 'default'"
size="small"
>
{{ permission.name }}
</Tag>
</div>
<span v-else class="text-gray-400">-</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space size="small" :wrap="false">
<Button type="link" size="small" @click="handleAddChild(row)">
<PlusCircleIcon class="h-3 w-3" />
增加下级
</Button>
<Button type="link" size="small" @click="handleEdit(row)">
<EditIcon class="h-3 w-3" />
编辑
</Button>
<Popconfirm
title="确定要删除这个菜单吗?"
@confirm="handleDelete(row)"
>
<Button type="link" size="small" danger>
<TrashIcon class="h-3 w-3" />
删除
</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<!-- 菜单表单模态框 -->
<MenuFormModal ref="menuFormModalRef" @success="handleModalSuccess" />
</Page>
</template>
<style scoped>
:deep(.menu-grid .vxe-body--column) {
vertical-align: middle;
}
</style>