mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 优化系统菜单和权限管理页
This commit is contained in:
+1
-1
@@ -71,7 +71,7 @@ public class MenuController {
|
||||
}
|
||||
|
||||
@PostMapping("/batch-sort")
|
||||
@RequirePermission(value = "sys:menu:update", description = "批量菜单排序", allowSuper = true)
|
||||
@RequirePermission(value = "sys:menu:update", description = "批量菜单排序与移动", allowSuper = true)
|
||||
public ApiResponse<Void> batchSortMenu(@Valid @RequestBody BatchSortMenuDTO batchSortMenuDTO) {
|
||||
menuService.batchSortMenu(batchSortMenuDTO);
|
||||
return ApiResponse.success("菜单排序成功");
|
||||
|
||||
+10
-16
@@ -1,5 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.menu.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
@@ -8,36 +10,28 @@ import lombok.NoArgsConstructor;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量菜单排序DTO
|
||||
* 批量菜单排序/移动(可同时改 parentId 与同级 order)
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BatchSortMenuDTO {
|
||||
|
||||
/**
|
||||
* 菜单排序项列表
|
||||
*/
|
||||
@NotNull(message = "菜单排序项列表不能为空")
|
||||
@NotEmpty(message = "菜单排序项列表不能为空")
|
||||
@Valid
|
||||
private List<MenuSortItem> sortItems;
|
||||
|
||||
/**
|
||||
* 菜单排序项
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class MenuSortItem {
|
||||
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
|
||||
@NotNull(message = "菜单ID不能为空")
|
||||
private Long menuId;
|
||||
|
||||
/**
|
||||
* 排序值
|
||||
*/
|
||||
|
||||
/** 新父级;null 表示挂到顶级 */
|
||||
private Long parentId;
|
||||
|
||||
@NotNull(message = "排序值不能为空")
|
||||
private Integer order;
|
||||
}
|
||||
|
||||
+28
-9
@@ -217,26 +217,45 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuPO> implements
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量菜单排序
|
||||
* @param batchSortMenuDTO 批量排序DTO
|
||||
* 批量菜单排序/移动
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void batchSortMenu(BatchSortMenuDTO batchSortMenuDTO) {
|
||||
log.info("批量菜单排序,排序项数量:{}", batchSortMenuDTO.getSortItems().size());
|
||||
|
||||
// 批量更新菜单排序
|
||||
for (BatchSortMenuDTO.MenuSortItem sortItem : batchSortMenuDTO.getSortItems()) {
|
||||
List<BatchSortMenuDTO.MenuSortItem> items = batchSortMenuDTO.getSortItems();
|
||||
log.info("批量菜单排序/移动,数量:{}", items.size());
|
||||
|
||||
for (BatchSortMenuDTO.MenuSortItem sortItem : items) {
|
||||
MenuPO menuPO = this.getById(sortItem.getMenuId());
|
||||
if (menuPO == null) {
|
||||
throw new BusinessException("菜单不存在,ID:" + sortItem.getMenuId());
|
||||
}
|
||||
|
||||
assertValidMenuParent(sortItem.getMenuId(), sortItem.getParentId());
|
||||
menuPO.setParentId(sortItem.getParentId());
|
||||
menuPO.setOrder(sortItem.getOrder());
|
||||
menuPO.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
this.updateById(menuPO);
|
||||
}
|
||||
|
||||
log.info("批量菜单排序完成");
|
||||
|
||||
log.info("批量菜单排序/移动完成");
|
||||
}
|
||||
|
||||
/** 父级合法:存在、且不能是自己或子孙 */
|
||||
private void assertValidMenuParent(Long menuId, Long parentId) {
|
||||
if (parentId == null) {
|
||||
return;
|
||||
}
|
||||
if (parentId.equals(menuId)) {
|
||||
throw new BusinessException("不能将菜单挂到自身下");
|
||||
}
|
||||
MenuPO parent = this.getById(parentId);
|
||||
if (parent == null) {
|
||||
throw new BusinessException("父菜单不存在");
|
||||
}
|
||||
List<Long> descendants = baseMapper.selectChildMenuIds(menuId);
|
||||
if (descendants != null && descendants.contains(parentId)) {
|
||||
throw new BusinessException("不能将菜单挂到其子孙节点下");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ public class PermissionController {
|
||||
}
|
||||
|
||||
@PutMapping("/sort")
|
||||
@RequirePermission(value = "sys:permission:update", description = "批量更新权限排序", allowSuper = true)
|
||||
@RequirePermission(value = "sys:permission:manage", description = "批量更新权限排序与父级", allowSuper = true)
|
||||
public ApiResponse<Void> batchSortPermission(
|
||||
@RequestBody @Valid BatchSortPermissionDTO dto) {
|
||||
permissionService.batchSortPermission(dto);
|
||||
|
||||
+8
-2
@@ -1,5 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.permission.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
@@ -8,14 +10,15 @@ import lombok.NoArgsConstructor;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量权限排序DTO
|
||||
* 批量权限排序/移动(可同时改 parentId 与同级 sortOrder)
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BatchSortPermissionDTO {
|
||||
|
||||
@NotNull(message = "排序项列表不能为空")
|
||||
@NotEmpty(message = "排序项列表不能为空")
|
||||
@Valid
|
||||
private List<SortItem> sortItems;
|
||||
|
||||
@Data
|
||||
@@ -26,6 +29,9 @@ public class BatchSortPermissionDTO {
|
||||
@NotNull(message = "权限ID不能为空")
|
||||
private Long permissionId;
|
||||
|
||||
/** 新父级;null 表示挂到顶级 */
|
||||
private Long parentId;
|
||||
|
||||
@NotNull(message = "排序值不能为空")
|
||||
private Integer sortOrder;
|
||||
}
|
||||
|
||||
+72
-25
@@ -1,15 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.permission.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.permission.service.CompanyPermissionService;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.position.permission.service.PositionPermissionService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.permission.mapper.PermissionMapper;
|
||||
@@ -48,14 +50,8 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
|
||||
@Override
|
||||
public PermissionVO createPermission(CreatePermissionDTO dto) {
|
||||
LambdaQueryWrapper<PermissionPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(PermissionPO::getCode, dto.getCode());
|
||||
if (dto.getParentId() != null) {
|
||||
queryWrapper.eq(PermissionPO::getParentId, dto.getParentId());
|
||||
}
|
||||
if (permissionMapper.selectCount(queryWrapper) > 0) {
|
||||
throw new BusinessException("该父节点下已存在相同权限码");
|
||||
}
|
||||
assertValidParent(null, dto.getParentId());
|
||||
assertCodeUniqueUnderParent(dto.getCode(), dto.getParentId(), null);
|
||||
|
||||
PermissionPO po = new PermissionPO();
|
||||
BeanCopyUtils.copyProperties(dto, po);
|
||||
@@ -72,22 +68,22 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
PermissionPO existing = permissionMapper.selectById(id);
|
||||
if (existing == null) throw new BusinessException("权限不存在");
|
||||
|
||||
LambdaQueryWrapper<PermissionPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(PermissionPO::getCode, dto.getCode())
|
||||
.ne(PermissionPO::getId, id);
|
||||
if (dto.getParentId() != null) {
|
||||
queryWrapper.eq(PermissionPO::getParentId, dto.getParentId());
|
||||
}
|
||||
if (permissionMapper.selectCount(queryWrapper) > 0) {
|
||||
throw new BusinessException("该父节点下已存在相同权限码");
|
||||
}
|
||||
assertValidParent(id, dto.getParentId());
|
||||
assertCodeUniqueUnderParent(dto.getCode(), dto.getParentId(), id);
|
||||
|
||||
BeanCopyUtils.copyProperties(dto, existing);
|
||||
existing.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
permissionMapper.updateById(existing);
|
||||
return convertToVO(existing);
|
||||
LambdaUpdateWrapper<PermissionPO> uw = new LambdaUpdateWrapper<>();
|
||||
uw.eq(PermissionPO::getId, id)
|
||||
.set(PermissionPO::getParentId, dto.getParentId())
|
||||
.set(PermissionPO::getCode, dto.getCode())
|
||||
.set(PermissionPO::getName, dto.getName())
|
||||
.set(PermissionPO::getType, dto.getType())
|
||||
.set(PermissionPO::getStatus, dto.getStatus() != null ? dto.getStatus() : existing.getStatus())
|
||||
.set(PermissionPO::getRemark, dto.getRemark())
|
||||
.set(PermissionPO::getSortOrder, dto.getSortOrder() != null ? dto.getSortOrder() : existing.getSortOrder())
|
||||
.set(PermissionPO::getUpdateBy, currentUserContext.getCurrentUserId());
|
||||
permissionMapper.update(null, uw);
|
||||
return convertToVO(permissionMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deletePermission(Long id) {
|
||||
PermissionPO permission = permissionMapper.selectById(id);
|
||||
@@ -248,9 +244,60 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void batchSortPermission(BatchSortPermissionDTO dto) {
|
||||
log.info("批量权限排序,数量:{}", dto.getSortItems().size());
|
||||
permissionMapper.batchUpdateSortOrder(dto.getSortItems());
|
||||
List<BatchSortPermissionDTO.SortItem> items = dto.getSortItems();
|
||||
log.info("批量权限排序/移动,数量:{}", items.size());
|
||||
for (BatchSortPermissionDTO.SortItem item : items) {
|
||||
PermissionPO po = permissionMapper.selectById(item.getPermissionId());
|
||||
if (po == null) {
|
||||
throw new BusinessException("权限不存在,ID:" + item.getPermissionId());
|
||||
}
|
||||
assertValidParent(item.getPermissionId(), item.getParentId());
|
||||
assertCodeUniqueUnderParent(po.getCode(), item.getParentId(), item.getPermissionId());
|
||||
}
|
||||
permissionMapper.batchUpdateSortOrder(items);
|
||||
}
|
||||
|
||||
/** 父级合法:存在、且不能是自己或子孙 */
|
||||
private void assertValidParent(Long permissionId, Long parentId) {
|
||||
if (parentId == null) {
|
||||
return;
|
||||
}
|
||||
if (permissionId != null && parentId.equals(permissionId)) {
|
||||
throw new BusinessException("不能将权限挂到自身下");
|
||||
}
|
||||
PermissionPO parent = permissionMapper.selectById(parentId);
|
||||
if (parent == null) {
|
||||
throw new BusinessException("父级权限不存在");
|
||||
}
|
||||
if (permissionId == null) {
|
||||
return;
|
||||
}
|
||||
List<Long> descendants = permissionMapper.selectChildPermissionIds(permissionId);
|
||||
if (descendants != null && descendants.contains(parentId)) {
|
||||
throw new BusinessException("不能将权限挂到其子孙节点下");
|
||||
}
|
||||
}
|
||||
|
||||
/** 同一父级下权限码唯一 */
|
||||
private void assertCodeUniqueUnderParent(String code, Long parentId, Long excludeId) {
|
||||
if (code == null || code.isBlank()) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<PermissionPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(PermissionPO::getCode, code);
|
||||
if (excludeId != null) {
|
||||
queryWrapper.ne(PermissionPO::getId, excludeId);
|
||||
}
|
||||
if (parentId != null) {
|
||||
queryWrapper.eq(PermissionPO::getParentId, parentId);
|
||||
} else {
|
||||
queryWrapper.isNull(PermissionPO::getParentId);
|
||||
}
|
||||
if (permissionMapper.selectCount(queryWrapper) > 0) {
|
||||
throw new BusinessException("该父节点下已存在相同权限码");
|
||||
}
|
||||
}
|
||||
|
||||
private PermissionVO convertToVO(PermissionPO po) {
|
||||
|
||||
@@ -37,14 +37,19 @@
|
||||
SELECT id FROM ancestor_tree
|
||||
</select>
|
||||
|
||||
<!-- 批量更新权限排序 -->
|
||||
<!-- 批量更新权限父级与排序 -->
|
||||
<update id="batchUpdateSortOrder">
|
||||
UPDATE sys_permission
|
||||
<trim prefix="SET" suffixOverrides=",">
|
||||
sort_order =
|
||||
<foreach collection="sortItems" item="item" separator=" " open="CASE id " close="END">
|
||||
WHEN #{item.permissionId} THEN #{item.sortOrder}
|
||||
</foreach>
|
||||
</foreach>,
|
||||
parent_id =
|
||||
<foreach collection="sortItems" item="item" separator=" " open="CASE id " close="END">
|
||||
WHEN #{item.permissionId} THEN #{item.parentId,jdbcType=BIGINT}
|
||||
</foreach>,
|
||||
update_time = CURRENT_TIMESTAMP
|
||||
</trim>
|
||||
WHERE id IN
|
||||
<foreach collection="sortItems" item="item" open="(" separator="," close=")">
|
||||
|
||||
@@ -73,7 +73,9 @@ export namespace MenuDTO {
|
||||
export interface MenuSortItem {
|
||||
/** 菜单ID */
|
||||
menuId: number;
|
||||
/** 排序值 */
|
||||
/** 新父级;null 表示顶级 */
|
||||
parentId?: null | number;
|
||||
/** 同级排序值 */
|
||||
order: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,8 +78,10 @@ export async function getSystemPermissionTreeApi() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新权限排序
|
||||
* 批量更新权限排序与父级(跨父拖拽)
|
||||
*/
|
||||
export async function batchSortPermissionApi(sortItems: { permissionId: number; sortOrder: number }[]) {
|
||||
export async function batchSortPermissionApi(
|
||||
sortItems: PermissionDTO.SortItem[],
|
||||
) {
|
||||
return requestClient.put('/permission/sort', { sortItems });
|
||||
}
|
||||
|
||||
@@ -5,32 +5,47 @@
|
||||
export namespace PermissionDTO {
|
||||
/** 创建权限参数 */
|
||||
export interface CreatePermissionDTO {
|
||||
/** 父权限ID(NULL=顶级) */
|
||||
parentId?: null | number;
|
||||
/** 权限码(唯一标识,如 user:add, order:approve) */
|
||||
code: string;
|
||||
/** 权限名称(用于显示,如 用户新增、订单审核) */
|
||||
name: string;
|
||||
/** 权限类型(api-接口权限,button-按钮权限,data-数据权限) */
|
||||
/** 权限类型(api/button/data/module) */
|
||||
type: string;
|
||||
/** 状态:1-启用 0-禁用 */
|
||||
status?: number;
|
||||
/** 同级排序 */
|
||||
sortOrder?: number;
|
||||
/** 备注 */
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/** 更新权限参数 */
|
||||
export interface UpdatePermissionDTO {
|
||||
/** 父权限ID(NULL=顶级) */
|
||||
parentId?: null | number;
|
||||
/** 权限码(唯一标识,如 user:add, order:approve) */
|
||||
code: string;
|
||||
/** 权限名称(用于显示,如 用户新增、订单审核) */
|
||||
name: string;
|
||||
/** 权限类型(api-接口权限,button-按钮权限,data-数据权限) */
|
||||
/** 权限类型(api/button/data/module) */
|
||||
type: string;
|
||||
/** 状态:1-启用 0-禁用 */
|
||||
status?: number;
|
||||
/** 同级排序 */
|
||||
sortOrder?: number;
|
||||
/** 备注 */
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/** 批量排序/移动项 */
|
||||
export interface SortItem {
|
||||
permissionId: number;
|
||||
parentId?: null | number;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
/** 权限过滤条件 */
|
||||
export interface PermissionFilterDTO {
|
||||
/** 权限码 */
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts" setup>
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { MenuVO } from '#/api/sys/menu/types';
|
||||
import type { MenuDTO, MenuVO } from '#/api/sys/menu/types';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
|
||||
@@ -124,14 +124,17 @@ const gridOptions: VxeGridProps<any> = {
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: {
|
||||
useKey: true,
|
||||
isHover: true,
|
||||
drag: true, // 启用行拖拽
|
||||
drag: true,
|
||||
height: 52,
|
||||
},
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
rowDragConfig: {
|
||||
isPeerDrag: true, // 启用同层级拖拽限制
|
||||
isCrossDrag: true,
|
||||
isToChildDrag: true,
|
||||
isSelfToChildDrag: true,
|
||||
},
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
@@ -317,38 +320,50 @@ function handleModalSuccess(
|
||||
// 防重复调用标志
|
||||
let isUpdating = false;
|
||||
|
||||
// 处理拖拽排序
|
||||
const handleDragSort = async (_params: any) => {
|
||||
// 防止重复调用
|
||||
/** 从树节点递归收集 parentId + 同级 order(VXE tree 的 fullData 是根节点树) */
|
||||
function collectMenuSortItems(
|
||||
nodes: any[],
|
||||
parentId: null | number = null,
|
||||
): MenuDTO.MenuSortItem[] {
|
||||
const items: MenuDTO.MenuSortItem[] = [];
|
||||
(nodes || []).forEach((node, index) => {
|
||||
if (node?.id == null) {
|
||||
return;
|
||||
}
|
||||
items.push({
|
||||
menuId: node.id,
|
||||
parentId,
|
||||
order: index + 1,
|
||||
});
|
||||
const children = node.children;
|
||||
if (Array.isArray(children) && children.length > 0) {
|
||||
items.push(...collectMenuSortItems(children, node.id));
|
||||
}
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
// 处理拖拽排序/跨父移动
|
||||
const handleDragSort = async () => {
|
||||
if (isUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isUpdating = true;
|
||||
const vxeGrid = (gridApi as any).grid;
|
||||
if (!vxeGrid) return;
|
||||
const treeRoots = vxeGrid.getTableData?.()?.fullData || [];
|
||||
if (!treeRoots.length) return;
|
||||
|
||||
// 获取当前表格数据
|
||||
const tableDataResult = gridApi.grid.getTableData();
|
||||
const tableData = tableDataResult?.tableData || [];
|
||||
const sortItems = collectMenuSortItems(treeRoots);
|
||||
if (!sortItems.length) return;
|
||||
|
||||
// 构建排序数据
|
||||
const sortItems = tableData.map((item: MenuVO.MenuInfo, index: number) => ({
|
||||
menuId: item.id,
|
||||
order: index + 1, // 排序值从1开始
|
||||
}));
|
||||
|
||||
// 调用排序接口
|
||||
await batchSortMenuApi({ sortItems });
|
||||
|
||||
// 排序成功后不需要重新加载数据,因为表格数据已经更新
|
||||
message.success('已保存排序');
|
||||
} catch (error: any) {
|
||||
console.error('拖拽排序失败:', error);
|
||||
if (error?.message) {
|
||||
message.error(error.message);
|
||||
} else {
|
||||
message.error('排序更新失败');
|
||||
}
|
||||
// 排序失败时重新加载数据,恢复原始状态
|
||||
message.error(error?.message || '排序更新失败');
|
||||
gridApi.reload();
|
||||
} finally {
|
||||
isUpdating = false;
|
||||
@@ -399,44 +414,21 @@ function getMenuTypeColor(type: string) {
|
||||
return colorMap[type] || 'default';
|
||||
}
|
||||
|
||||
// 创建 VbenVxeGrid 实例
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '菜单管理',
|
||||
gridEvents: {
|
||||
// 拖拽排序事件
|
||||
rowDragend: handleDragSort,
|
||||
cellMenu: onCellMenu,
|
||||
} 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">
|
||||
<Grid :loading="loading" class="menu-grid">
|
||||
<!-- 工具栏工具 -->
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
@@ -453,7 +445,8 @@ onMounted(() => {
|
||||
全部收起
|
||||
</Button>
|
||||
<div class="text-sm text-gray-500">
|
||||
💡 可拖拽菜单名称列排序;右键行可编辑 / 增下级 / 删除
|
||||
支持跨父级拖拽(按住 Ctrl
|
||||
可拖成目标子节点);右键行可编辑 / 增下级 / 删除
|
||||
</div>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
+3
-2
@@ -14,7 +14,7 @@ import {
|
||||
} from '#/api/sys/permission';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
(e: 'success', payload?: { parentId?: null | number }): void;
|
||||
}
|
||||
|
||||
defineOptions({ name: 'PermissionFormModal' });
|
||||
@@ -67,6 +67,7 @@ const formData = ref<FormData>({
|
||||
|
||||
// 权限类型选项
|
||||
const typeOptions = [
|
||||
{ label: '模块分组', value: 'module' },
|
||||
{ label: '接口权限', value: 'api' },
|
||||
{ label: '按钮权限', value: 'button' },
|
||||
{ label: '数据权限', value: 'data' },
|
||||
@@ -209,7 +210,7 @@ async function handleSubmit() {
|
||||
}
|
||||
|
||||
close();
|
||||
emit('success');
|
||||
emit('success', { parentId: formData.value.parentId });
|
||||
} catch (error: any) {
|
||||
console.error('保存权限失败:', error);
|
||||
const errorMessage =
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { PermissionVO } from '#/api/sys/permission';
|
||||
|
||||
import { ref } from 'vue';
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
@@ -28,6 +28,8 @@ const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const PlusCircleIcon = createIconifyIcon('lucide:plus-circle');
|
||||
const EditIcon = createIconifyIcon('lucide:edit');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
const UnfoldIcon = createIconifyIcon('lucide:unfold-vertical');
|
||||
const FoldIcon = createIconifyIcon('lucide:fold-vertical');
|
||||
|
||||
const loading = ref(false);
|
||||
const permissionFormModalRef = ref();
|
||||
@@ -58,6 +60,7 @@ const gridOptions: VxeGridProps<any> = {
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
treeNode: true,
|
||||
dragSort: true,
|
||||
},
|
||||
{
|
||||
field: 'code',
|
||||
@@ -106,12 +109,15 @@ const gridOptions: VxeGridProps<any> = {
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
rowConfig: {
|
||||
useKey: true,
|
||||
isHover: true,
|
||||
drag: true,
|
||||
height: 52,
|
||||
},
|
||||
rowDragConfig: {
|
||||
isPeerDrag: false,
|
||||
isCrossDrag: true,
|
||||
isToChildDrag: true,
|
||||
isSelfToChildDrag: true,
|
||||
},
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
@@ -150,29 +156,114 @@ const gridOptions: VxeGridProps<any> = {
|
||||
|
||||
let isDragging = false;
|
||||
|
||||
/** 从树节点递归收集 parentId + 同级 sortOrder(VXE tree 的 fullData 是根节点树,不是扁平列表) */
|
||||
function collectPermissionSortItems(
|
||||
nodes: any[],
|
||||
parentId: null | number = null,
|
||||
): {
|
||||
permissionId: number;
|
||||
parentId: null | number;
|
||||
sortOrder: number;
|
||||
}[] {
|
||||
const items: {
|
||||
permissionId: number;
|
||||
parentId: null | number;
|
||||
sortOrder: number;
|
||||
}[] = [];
|
||||
(nodes || []).forEach((node, index) => {
|
||||
if (node?.id == null) {
|
||||
return;
|
||||
}
|
||||
items.push({
|
||||
permissionId: node.id,
|
||||
parentId,
|
||||
sortOrder: index + 1,
|
||||
});
|
||||
const children = node.children;
|
||||
if (Array.isArray(children) && children.length > 0) {
|
||||
items.push(...collectPermissionSortItems(children, node.id));
|
||||
}
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 拖拽结束后按树结构写回 parentId + sortOrder */
|
||||
async function handleDragSort() {
|
||||
if (isDragging) return;
|
||||
isDragging = true;
|
||||
try {
|
||||
const vxeGrid = (gridApi as any).grid;
|
||||
if (!vxeGrid) return;
|
||||
const tableData = vxeGrid.getTableData?.()?.fullData || [];
|
||||
if (!tableData.length) return;
|
||||
const sortItems = tableData.map((item: any, index: number) => ({
|
||||
permissionId: item.id,
|
||||
sortOrder: index + 1,
|
||||
}));
|
||||
// treeConfig 开启时 fullData = 根节点树(含 children),不是扁平全量
|
||||
const treeRoots = vxeGrid.getTableData?.()?.fullData || [];
|
||||
if (!treeRoots.length) return;
|
||||
|
||||
const sortItems = collectPermissionSortItems(treeRoots);
|
||||
if (!sortItems.length) return;
|
||||
|
||||
await batchSortPermissionApi(sortItems);
|
||||
message.success('已保存排序');
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '排序更新失败');
|
||||
gridApi.reload();
|
||||
await refreshTable();
|
||||
} finally {
|
||||
isDragging = false;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshTable() {
|
||||
if (gridApi) gridApi.reload();
|
||||
function getExpandedPermissionIds(): number[] {
|
||||
const grid = (gridApi as any)?.grid;
|
||||
if (!grid?.getTreeExpandRecords) {
|
||||
return [];
|
||||
}
|
||||
return (grid.getTreeExpandRecords() as PermissionVO.PermissionInfoVO[])
|
||||
.map((row) => row.id)
|
||||
.filter((id): id is number => id != null);
|
||||
}
|
||||
|
||||
async function restoreTreeExpand(expandedIds: Iterable<number>) {
|
||||
const idSet = new Set(expandedIds);
|
||||
if (idSet.size === 0) {
|
||||
return;
|
||||
}
|
||||
await nextTick();
|
||||
const grid = (gridApi as any)?.grid;
|
||||
if (!grid?.setTreeExpand) {
|
||||
return;
|
||||
}
|
||||
const fullData =
|
||||
(grid.getTableData?.()?.fullData as PermissionVO.PermissionInfoVO[]) || [];
|
||||
const rows = fullData.filter((row) => row.id != null && idSet.has(row.id));
|
||||
if (rows.length > 0) {
|
||||
await grid.setTreeExpand(rows, true);
|
||||
}
|
||||
}
|
||||
|
||||
/** 刷新并尽量保持展开状态;extraExpandIds 用于新建后展开父节点 */
|
||||
async function refreshTable(extraExpandIds: number[] = []) {
|
||||
if (!gridApi) {
|
||||
return;
|
||||
}
|
||||
const expandedIds = new Set([
|
||||
...getExpandedPermissionIds(),
|
||||
...extraExpandIds,
|
||||
]);
|
||||
await gridApi.reload();
|
||||
await restoreTreeExpand(expandedIds);
|
||||
}
|
||||
|
||||
function expandAllTree() {
|
||||
const vxeTable = (gridApi as any)?.grid;
|
||||
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
|
||||
vxeTable.setAllTreeExpand(true);
|
||||
}
|
||||
}
|
||||
|
||||
function collapseAllTree() {
|
||||
const vxeTable = (gridApi as any)?.grid;
|
||||
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
|
||||
vxeTable.setAllTreeExpand(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
@@ -191,7 +282,7 @@ async function handleDelete(row: PermissionVO.PermissionInfoVO) {
|
||||
try {
|
||||
await deletePermissionApi(row.id);
|
||||
message.success('删除成功');
|
||||
refreshTable();
|
||||
await refreshTable();
|
||||
} catch (error: any) {
|
||||
message.error(
|
||||
error?.response?.data?.message || error?.message || '删除失败',
|
||||
@@ -263,8 +354,10 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
} as any,
|
||||
});
|
||||
|
||||
function handleModalSuccess() {
|
||||
refreshTable();
|
||||
async function handleModalSuccess(payload?: { parentId?: null | number }) {
|
||||
const extra =
|
||||
payload?.parentId != null ? [payload.parentId] : ([] as number[]);
|
||||
await refreshTable(extra);
|
||||
}
|
||||
|
||||
const getTypeText = (type: string) => {
|
||||
@@ -292,7 +385,8 @@ const getTypeColor = (type: string) => {
|
||||
<Page title="系统权限" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
平台完整权限树结构,支持拖拽排序;右键行可增加下级 / 编辑 / 删除
|
||||
支持跨父级拖拽(按住 Ctrl 可拖成目标子节点);右键行可增加下级 /
|
||||
编辑 / 删除
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -303,6 +397,14 @@ const getTypeColor = (type: string) => {
|
||||
<PlusIcon />
|
||||
添加权限
|
||||
</Button>
|
||||
<Button @click="expandAllTree">
|
||||
<UnfoldIcon class="h-4 w-4" />
|
||||
全部展开
|
||||
</Button>
|
||||
<Button @click="collapseAllTree">
|
||||
<FoldIcon class="h-4 w-4" />
|
||||
全部收起
|
||||
</Button>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user