feat: 新增右键菜单二次封装 系统菜单和权限使用

This commit is contained in:
2026-08-16 10:21:12 +08:00
parent e5565956ba
commit ce349a5ec7
7 changed files with 432 additions and 48 deletions
@@ -0,0 +1,129 @@
<script lang="ts" setup>
import type { VxeRowContextMenuItem } from './types';
import { computed, h, onBeforeUnmount, watch } from 'vue';
import { Menu } from 'ant-design-vue';
defineOptions({ name: 'VxeRowContextMenu' });
const props = defineProps<{
open: boolean;
x: number;
y: number;
items: VxeRowContextMenuItem[];
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
select: [key: string];
}>();
const menuItems = computed(() =>
props.items.map((item) => {
if (item.divider) {
return { type: 'divider' as const, key: item.key };
}
return {
key: item.key,
label: item.label,
danger: item.danger,
disabled: item.disabled,
icon: item.icon
? () => h(item.icon!, { class: 'size-4 shrink-0' })
: undefined,
};
}),
);
const panelStyle = computed(() => ({
left: `${props.x}px`,
top: `${props.y}px`,
}));
function close() {
emit('update:open', false);
}
function onMenuClick(info: { key: string | number }) {
emit('select', String(info.key));
close();
}
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Escape' && props.open) {
close();
}
}
watch(
() => props.open,
(open) => {
if (open) {
document.addEventListener('keydown', onKeydown);
} else {
document.removeEventListener('keydown', onKeydown);
}
},
);
onBeforeUnmount(() => {
document.removeEventListener('keydown', onKeydown);
});
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-[1040]"
@mousedown="close"
@contextmenu.prevent="close"
/>
<div
v-if="open"
class="vxe-row-ctx-panel fixed z-[1050] min-w-[160px] overflow-hidden rounded-lg bg-white py-1 shadow-[0_6px_16px_0_rgba(0,0,0,0.08),0_3px_6px_-4px_rgba(0,0,0,0.12),0_9px_28px_8px_rgba(0,0,0,0.05)] dark:bg-[hsl(222.34deg_10.43%_14%)] dark:shadow-[0_6px_16px_0_rgba(0,0,0,0.4)]"
:style="panelStyle"
@mousedown.stop
>
<Menu
class="vxe-row-ctx-menu !border-0 !bg-transparent !shadow-none"
:items="menuItems"
@click="onMenuClick"
/>
</div>
</Teleport>
</template>
<style scoped>
:deep(.vxe-row-ctx-menu.ant-menu-vertical) {
border-inline-end: none !important;
}
:deep(.vxe-row-ctx-menu .ant-menu-item) {
margin-block: 2px;
margin-inline: 4px;
width: calc(100% - 8px);
height: 32px;
line-height: 32px;
border-radius: 6px;
display: flex;
align-items: center;
gap: 8px;
}
:deep(.vxe-row-ctx-menu .ant-menu-item .anticon),
:deep(.vxe-row-ctx-menu .ant-menu-item .ant-menu-item-icon) {
font-size: 14px;
}
:deep(.vxe-row-ctx-menu .ant-menu-item-danger) {
color: #ff4d4f;
}
:deep(.vxe-row-ctx-menu .ant-menu-item-danger:hover),
:deep(.vxe-row-ctx-menu .ant-menu-item-danger-selected) {
color: #ff4d4f !important;
background: #fff2f0 !important;
}
</style>
@@ -0,0 +1,6 @@
export { default as VxeRowContextMenu } from './VxeRowContextMenu.vue';
export type {
VxeRowContextMenuItem,
VxeRowContextMenuItemsFactory,
} from './types';
export { useVxeRowContextMenu } from './use-vxe-row-context-menu';
@@ -0,0 +1,15 @@
import type { Component } from 'vue';
/** 表格行右键菜单项(Ant Design Menu 风格) */
export interface VxeRowContextMenuItem {
key: string;
label: string;
icon?: Component;
danger?: boolean;
disabled?: boolean;
divider?: boolean;
}
export type VxeRowContextMenuItemsFactory<T = any> = (
row: T,
) => VxeRowContextMenuItem[];
@@ -0,0 +1,69 @@
import type {
VxeRowContextMenuItem,
VxeRowContextMenuItemsFactory,
} from './types';
import { ref } from 'vue';
/**
* 配合 VxeGrid `cell-menu`:拦截 Vxe 默认右键面板,弹出 Ant Design 风格菜单。
* gridOptions.menuConfig 需 enabled + visibleMethod: () => false。
*/
export function useVxeRowContextMenu<T = any>(
itemsFactory: VxeRowContextMenuItemsFactory<T>,
) {
const open = ref(false);
const x = ref(0);
const y = ref(0);
const row = ref<T | null>(null);
const items = ref<VxeRowContextMenuItem[]>([]);
function close() {
open.value = false;
row.value = null;
items.value = [];
}
function clamp(clientX: number, clientY: number, itemCount: number) {
const menuW = 168;
const menuH = Math.max(40, itemCount * 36 + 12);
return {
x: Math.max(8, Math.min(clientX, window.innerWidth - menuW - 8)),
y: Math.max(8, Math.min(clientY, window.innerHeight - menuH - 8)),
};
}
/** 绑到 gridEvents.cellMenu */
function onCellMenu(params: { row?: T; $event?: MouseEvent }) {
const e = params.$event;
if (e) {
e.preventDefault();
e.stopPropagation();
}
if (!params.row) {
close();
return;
}
const nextItems = itemsFactory(params.row) ?? [];
const pos = clamp(e?.clientX ?? 0, e?.clientY ?? 0, nextItems.length);
row.value = params.row;
items.value = nextItems;
x.value = pos.x;
y.value = pos.y;
// 先关再开,保证连续右键不同行时位置/内容刷新
open.value = false;
requestAnimationFrame(() => {
open.value = true;
});
}
return {
open,
x,
y,
row,
items,
close,
onCellMenu,
};
}
@@ -7,7 +7,7 @@ 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 { Button, message, Modal, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
@@ -15,6 +15,10 @@ import {
deleteMenuApi,
getAllMenusApi,
} from '#/api/sys/menu';
import {
useVxeRowContextMenu,
VxeRowContextMenu,
} from '#/components/vxe-row-context-menu';
import MenuFormModal from './components/MenuFormModal.vue';
@@ -141,6 +145,12 @@ const gridOptions: VxeGridProps<any> = {
rowField: 'id',
parentField: 'parentId',
},
// 启用 cell-menu 事件,但隐藏 Vxe 原生面板(由 Ant Design 二次封装接管)
menuConfig: {
enabled: true,
trigger: 'cell',
visibleMethod: () => false,
},
// 配置远程加载
proxyConfig: {
ajax: {
@@ -237,6 +247,62 @@ async function handleDelete(record: MenuVO.MenuInfo) {
}
}
function confirmDeleteMenu(record: MenuVO.MenuInfo) {
Modal.confirm({
title: '确定要删除这个菜单吗?',
content: record.title || record.name || `ID ${record.id}`,
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: () => handleDelete(record),
});
}
const {
open: ctxMenuOpen,
x: ctxMenuX,
y: ctxMenuY,
row: ctxMenuRow,
items: ctxMenuItems,
onCellMenu,
} = useVxeRowContextMenu<MenuVO.MenuInfo>((_row) => [
{
key: 'addChild',
label: '新增',
icon: PlusCircleIcon,
},
{
key: 'edit',
label: '编辑',
icon: EditIcon,
},
{
key: 'delete',
label: '删除',
icon: TrashIcon,
danger: true,
},
]);
function handleCtxMenuSelect(key: string) {
const row = ctxMenuRow.value;
if (!row) return;
switch (key) {
case 'addChild': {
handleAddChild(row);
break;
}
case 'edit': {
handleEdit(row);
break;
}
case 'delete': {
confirmDeleteMenu(row);
break;
}
}
}
// 处理模态框成功:更新菜单只合并当前行;新建仍整表刷新
function handleModalSuccess(
payload?: { mode: 'update'; menu: MenuVO.MenuInfo } | { mode: 'create' },
@@ -341,6 +407,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
gridEvents: {
// 拖拽排序事件
rowDragend: handleDragSort,
cellMenu: onCellMenu,
} as any,
});
@@ -386,7 +453,7 @@ onMounted(() => {
全部收起
</Button>
<div class="text-sm text-gray-500">
💡 提示:可直接拖拽菜单名称列进行排序
💡 可拖拽菜单名称列排序;右键行可编辑 / 增下级 / 删除
</div>
</Space>
</template>
@@ -463,6 +530,14 @@ onMounted(() => {
<!-- 菜单表单模态框 -->
<MenuFormModal ref="menuFormModalRef" @success="handleModalSuccess" />
<VxeRowContextMenu
v-model:open="ctxMenuOpen"
:x="ctxMenuX"
:y="ctxMenuY"
:items="ctxMenuItems"
@select="handleCtxMenuSelect"
/>
</Page>
</template>
@@ -120,31 +120,45 @@ function close() {
formRef.value?.resetFields();
}
// 暴露给父组件的方法
function open(permissionData?: null | PermissionVO.PermissionInfoVO) {
isEdit.value = !!permissionData;
currentPermissionData.value = permissionData || null;
/**
* @param edit 是否编辑
* @param record 编辑时为当前行;新增下级时为父级行(自动填 parentId)
*/
function open(edit = false, record?: null | PermissionVO.PermissionInfoVO) {
isEdit.value = edit;
currentPermissionData.value = edit ? record || null : null;
modalApi.setState({
title: isEdit.value ? '编辑权限' : '添加权限',
title: edit ? '编辑权限' : record ? '增加下级权限' : '添加权限',
});
resetForm();
if (permissionData) {
if (edit && record) {
// 编辑时排除自己和子孙节点(不能选自己或子孙做父级)
const disabledIds = collectDescendantIds(permissionData);
const disabledIds = collectDescendantIds(record);
formData.value = {
code: permissionData.code,
name: permissionData.name,
type: permissionData.type,
parentId: permissionData.parentId ?? null,
sortOrder: permissionData.sortOrder ?? 0,
status: permissionData.status === 1,
remark: permissionData.remark || '',
code: record.code,
name: record.name,
type: record.type,
parentId: record.parentId ?? null,
sortOrder: record.sortOrder ?? 0,
status: record.status === 1,
remark: record.remark || '',
};
// 加载父级选项(编辑时传入禁用自己及子孙的集合)
loadParentPermissionsWithDisabled(disabledIds);
} else if (!edit && record) {
// 增加下级:父级默认当前行
formData.value = {
code: '',
name: '',
type: 'api',
parentId: record.id ?? null,
sortOrder: 0,
status: true,
remark: '',
};
loadParentPermissions();
} else {
loadParentPermissions();
}
@@ -7,7 +7,7 @@ import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { Button, message, Modal, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
@@ -15,19 +15,23 @@ import {
deletePermissionApi,
getSystemPermissionTreeApi,
} from '#/api/sys/permission';
import {
useVxeRowContextMenu,
VxeRowContextMenu,
} from '#/components/vxe-row-context-menu';
import PermissionFormModal from './components/PermissionFormModal.vue';
defineOptions({ name: 'PermissionManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const PlusCircleIcon = createIconifyIcon('lucide:plus-circle');
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
// 响应式数据
const loading = ref(false);
const permissionFormModalRef = ref();
// 扁平化树数据(VxeTable treeConfig.transform 需要扁平数据)
function flattenTree(
nodes: PermissionVO.PermissionInfoVO[],
result: PermissionVO.PermissionInfoVO[] = [],
@@ -41,7 +45,6 @@ function flattenTree(
return result;
}
// VxeGrid 树形表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
@@ -54,7 +57,7 @@ const gridOptions: VxeGridProps<any> = {
title: '权限名称',
minWidth: 200,
showOverflow: 'tooltip' as const,
treeNode: true, // 启用树节点显示
treeNode: true,
},
{
field: 'code',
@@ -92,7 +95,7 @@ const gridOptions: VxeGridProps<any> = {
},
{
title: '操作',
width: 120,
minWidth: 260,
fixed: 'right' as const,
slots: { default: 'action' },
},
@@ -121,6 +124,11 @@ const gridOptions: VxeGridProps<any> = {
rowField: 'id',
parentField: 'parentId',
},
menuConfig: {
enabled: true,
trigger: 'cell',
visibleMethod: () => false,
},
proxyConfig: {
ajax: {
query: async () => {
@@ -140,18 +148,8 @@ const gridOptions: VxeGridProps<any> = {
},
};
// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents: {
rowDragend: handleDragSort,
} as any,
});
// 防重调用标志
let isDragging = false;
// 处理拖拽排序
async function handleDragSort() {
if (isDragging) return;
isDragging = true;
@@ -160,7 +158,6 @@ async function handleDragSort() {
if (!vxeGrid) return;
const tableData = vxeGrid.getTableData?.()?.fullData || [];
if (!tableData.length) return;
// 按 tree 的顺序构建排序数据(VxeTable tree 内部已更新顺序)
const sortItems = tableData.map((item: any, index: number) => ({
permissionId: item.id,
sortOrder: index + 1,
@@ -174,22 +171,22 @@ async function handleDragSort() {
}
}
// 刷新表格
function refreshTable() {
if (gridApi) gridApi.reload();
}
// 打开新增
function handleAdd() {
permissionFormModalRef.value?.open();
permissionFormModalRef.value?.open(false);
}
function handleAddChild(row: PermissionVO.PermissionInfoVO) {
permissionFormModalRef.value?.open(false, row);
}
// 打开编辑
function handleEdit(row: PermissionVO.PermissionInfoVO) {
permissionFormModalRef.value?.open(row);
permissionFormModalRef.value?.open(true, row);
}
// 删除
async function handleDelete(row: PermissionVO.PermissionInfoVO) {
try {
await deletePermissionApi(row.id);
@@ -202,12 +199,74 @@ async function handleDelete(row: PermissionVO.PermissionInfoVO) {
}
}
// 表单弹窗成功回调
function confirmDeletePermission(row: PermissionVO.PermissionInfoVO) {
Modal.confirm({
title: '确定要删除这个权限吗?',
content: row.name || row.code || `ID ${row.id}`,
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: () => handleDelete(row),
});
}
const {
open: ctxMenuOpen,
x: ctxMenuX,
y: ctxMenuY,
row: ctxMenuRow,
items: ctxMenuItems,
onCellMenu,
} = useVxeRowContextMenu<PermissionVO.PermissionInfoVO>(() => [
{
key: 'addChild',
label: '增加下级',
icon: PlusCircleIcon,
},
{
key: 'edit',
label: '编辑',
icon: EditIcon,
},
{
key: 'delete',
label: '删除',
icon: TrashIcon,
danger: true,
},
]);
function handleCtxMenuSelect(key: string) {
const row = ctxMenuRow.value;
if (!row) return;
switch (key) {
case 'addChild': {
handleAddChild(row);
break;
}
case 'edit': {
handleEdit(row);
break;
}
case 'delete': {
confirmDeletePermission(row);
break;
}
}
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents: {
rowDragend: handleDragSort,
cellMenu: onCellMenu,
} as any,
});
function handleModalSuccess() {
refreshTable();
}
// 类型文本
const getTypeText = (type: string) => {
const typeMap: Record<string, string> = {
api: '接口权限',
@@ -233,7 +292,7 @@ const getTypeColor = (type: string) => {
<Page title="系统权限" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
平台完整权限树结构,支持拖拽排序
平台完整权限树结构,支持拖拽排序;右键行可增加下级 / 编辑 / 删除
</div>
</template>
@@ -260,23 +319,40 @@ const getTypeColor = (type: string) => {
</template>
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<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 size="small" danger>删除</Button>
<Button type="link" size="small" danger>
<TrashIcon class="h-3 w-3" />
删除
</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<!-- 权限表单弹窗 -->
<PermissionFormModal
ref="permissionFormModalRef"
@success="handleModalSuccess"
/>
<VxeRowContextMenu
v-model:open="ctxMenuOpen"
:x="ctxMenuX"
:y="ctxMenuY"
:items="ctxMenuItems"
@select="handleCtxMenuSelect"
/>
</Page>
</template>