feat: 权限树前端改造

- PermissionVO 新增 parentId、sortOrder、children 字段
- 新增 getPermissionTreeApi 接口
- 权限管理页新增树状视图(表格/树状切换)
- 职位权限分配页改为树状多选(父→子级联勾选)
- 公司权限分配页改为树状多选(父→子级联勾选)
- 勾选父节点自动勾选所有子权限和父节点链
This commit is contained in:
小蟑螂
2026-04-10 13:50:24 +08:00
parent 7e0da22f83
commit 1e9a6dcc34
5 changed files with 554 additions and 403 deletions
@@ -48,3 +48,10 @@ export async function getPermissionDetailApi(permissionId: number) {
export async function getAllPermissionsApi() { export async function getAllPermissionsApi() {
return requestClient.get<PermissionVO.PermissionInfoVO[]>('/permission/list'); return requestClient.get<PermissionVO.PermissionInfoVO[]>('/permission/list');
} }
/**
* 获取权限树(树状结构)
*/
export async function getPermissionTreeApi() {
return requestClient.get<PermissionVO.PermissionInfoVO[]>('/permission/tree');
}
@@ -7,16 +7,22 @@ export namespace PermissionVO {
export interface PermissionInfoVO { export interface PermissionInfoVO {
/** 权限ID */ /** 权限ID */
id: number; id: number;
/** 父权限ID(NULL=顶级模块) */
parentId?: number | null;
/** 权限码(唯一标识,如 user:add, order:approve) */ /** 权限码(唯一标识,如 user:add, order:approve) */
code: string; code: string;
/** 权限名称(用于显示,如 用户新增、订单审核) */ /** 权限名称(用于显示,如 用户新增、订单审核) */
name: string; name: string;
/** 权限类型(api-接口权限,button-按钮权限,data-数据权限) */ /** 权限类型(api-接口权限,button-按钮权限,data-数据权限,module-模块分组) */
type: string; type: string;
/** 状态:1-启用 0-禁用 */ /** 状态:1-启用 0-禁用 */
status: number; status: number;
/** 备注 */ /** 备注 */
remark?: string; remark?: string;
/** 同级排序 */
sortOrder?: number;
/** 子权限列表(树结构) */
children?: PermissionInfoVO[];
/** 创建时间 */ /** 创建时间 */
createTime: string; createTime: string;
/** 更新时间 */ /** 更新时间 */
@@ -1,7 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import type { PositionVO } from '#/api/organization/position/types'; import type { PositionVO } from '#/api/organization/position/types';
import type { PermissionVO } from '#/api/system/permission/types';
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
@@ -16,58 +17,50 @@ import {
Select, Select,
Spin, Spin,
Tag, Tag,
Tree,
} from 'ant-design-vue'; } from 'ant-design-vue';
import { unrefElement } from '@vueuse/core';
import { getPositionPageApi } from '#/api/organization/position'; import { getPositionPageApi } from '#/api/organization/position';
import { import {
batchUpdatePositionPermissionsApi, batchUpdatePositionPermissionsApi,
getAllPermissionsApi,
getPositionPermissionIdsApi, getPositionPermissionIdsApi,
} from '#/api/organization/position-permission-assign/apis'; } from '#/api/organization/position-permission-assign/apis';
import { getPermissionTreeApi } from '#/api/system/permission';
defineOptions({ defineOptions({ name: 'PositionPermissionAssignPage' });
name: 'PositionPermissionAssignPage',
});
// 搜索表单 // 搜索表单
const searchForm = ref({ const searchForm = ref({ name: '', status: undefined as number | undefined });
name: '',
status: undefined as number | undefined,
});
// 职位列表 // 职位列表
const positionList = ref<PositionVO.PositionInfoVO[]>([]); const positionList = ref<PositionVO.PositionInfoVO[]>([]);
const positionLoading = ref(false); const positionLoading = ref(false);
const positionPagination = ref({ const positionPagination = ref({ current: 1, pageSize: 10, total: 0 });
current: 1,
pageSize: 10,
total: 0,
});
// 当前选中的职位 // 当前选中的职位
const currentPosition = ref<null | PositionVO.PositionInfoVO>(null); const currentPosition = ref<null | PositionVO.PositionInfoVO>(null);
// 所有权限列表 // 权限树数据
const allPermissions = ref<any[]>([]); const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const permissionLoading = ref(false); const permissionLoading = ref(false);
// 当前岗位已分配的权限ID列表 // 当前岗位已分配的权限ID
const assignedPermissionIds = ref<number[]>([]); const assignedPermissionIds = ref<number[]>([]);
const selectedPermissionIds = ref<number[]>([]); const selectedPermissionIds = ref<number[]>([]);
// Ant Design Tree 的选中 key(只存叶子节点)
const checkedKeys = ref<number[]>([]);
// 搜索职位列表 // 搜索职位列表
async function searchPositions() { async function searchPositions() {
positionLoading.value = true; positionLoading.value = true;
try { try {
const params = { const result = await getPositionPageApi({
page: positionPagination.value.current, page: positionPagination.value.current,
pageSize: positionPagination.value.pageSize, pageSize: positionPagination.value.pageSize,
filters: { filters: { name: searchForm.value.name || undefined, status: searchForm.value.status },
name: searchForm.value.name || undefined, });
status: searchForm.value.status,
},
};
const result = await getPositionPageApi(params);
positionList.value = result.records; positionList.value = result.records;
positionPagination.value.total = result.total; positionPagination.value.total = result.total;
} catch (error: any) { } catch (error: any) {
@@ -77,14 +70,14 @@ async function searchPositions() {
} }
} }
// 加载所有权限 // 加载权限树
async function loadAllPermissions() { async function loadPermissionTree() {
permissionLoading.value = true; permissionLoading.value = true;
try { try {
const result = await getAllPermissionsApi(); const result = await getPermissionTreeApi();
allPermissions.value = result.data?.records || []; permissionTree.value = result.data || [];
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '获取权限列表失败'); message.error(error?.message || '获取权限树失败');
} finally { } finally {
permissionLoading.value = false; permissionLoading.value = false;
} }
@@ -96,15 +89,16 @@ async function selectPosition(position: PositionVO.PositionInfoVO) {
await loadAssignedPermissions(); await loadAssignedPermissions();
} }
// 加载职位已分配的权限ID列表 // 加载职位已分配的权限ID
async function loadAssignedPermissions() { async function loadAssignedPermissions() {
if (!currentPosition.value?.id) return; if (!currentPosition.value?.id) return;
permissionLoading.value = true; permissionLoading.value = true;
try { try {
const result = await getPositionPermissionIdsApi(currentPosition.value.id); const result = await getPositionPermissionIdsApi(currentPosition.value.id);
assignedPermissionIds.value = result; assignedPermissionIds.value = result || [];
selectedPermissionIds.value = [...result]; selectedPermissionIds.value = [...assignedPermissionIds.value];
// Tree 组件的 checkedKeys 直接用数字
checkedKeys.value = [...assignedPermissionIds.value];
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '获取职位权限失败'); message.error(error?.message || '获取职位权限失败');
} finally { } finally {
@@ -112,36 +106,11 @@ async function loadAssignedPermissions() {
} }
} }
// 切换单个权限
function togglePermission(permissionId: number, checked: boolean) {
if (checked) {
selectedPermissionIds.value.push(permissionId);
} else {
selectedPermissionIds.value = selectedPermissionIds.value.filter(
(id) => id !== permissionId,
);
}
}
// 全选
function selectAll() {
selectedPermissionIds.value = allPermissions.value.map((p) => p.id);
}
// 取消全选
function selectNone() {
selectedPermissionIds.value = [];
}
// 保存权限分配 // 保存权限分配
async function savePermissions() { async function savePermissions() {
if (!currentPosition.value?.id) return; if (!currentPosition.value?.id) return;
try { try {
await batchUpdatePositionPermissionsApi( await batchUpdatePositionPermissionsApi(currentPosition.value.id, selectedPermissionIds.value);
currentPosition.value.id,
selectedPermissionIds.value,
);
message.success('权限分配保存成功'); message.success('权限分配保存成功');
assignedPermissionIds.value = [...selectedPermissionIds.value]; assignedPermissionIds.value = [...selectedPermissionIds.value];
} catch (error: any) { } catch (error: any) {
@@ -149,26 +118,6 @@ async function savePermissions() {
} }
} }
// 按类型分组权限
const groupedPermissions = computed(() => {
const groups: Record<string, any[]> = {};
for (const perm of allPermissions.value) {
const type = perm.type || 'other';
if (!groups[type]) groups[type] = [];
groups[type].push(perm);
}
return groups;
});
// 统计信息
const stats = computed(() => {
const total = allPermissions.value.length;
const assigned = assignedPermissionIds.value.length;
const selected = selectedPermissionIds.value.length;
const changed = selected !== assigned;
return { total, assigned, selected, changed };
});
// 重置搜索 // 重置搜索
function resetSearch() { function resetSearch() {
searchForm.value = { name: '', status: undefined }; searchForm.value = { name: '', status: undefined };
@@ -183,10 +132,139 @@ function handlePageChange(page: number, pageSize: number) {
searchPositions(); searchPositions();
} }
// 初始化 // 统计
const stats = computed(() => {
const totalLeaf = countLeafPermissions(permissionTree.value);
const assigned = assignedPermissionIds.value.length;
const selected = selectedPermissionIds.value.length;
return { total: totalLeaf, assigned, selected, changed: selected !== assigned };
});
function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number {
let count = 0;
for (const node of nodes) {
if (node.children && node.children.length > 0) {
count += countLeafPermissions(node.children);
} else {
count++;
}
}
return count;
}
// 把权限树转成 Ant Design Tree 格式
function toAntdTreeData(nodes: PermissionVO.PermissionInfoVO[]): any[] {
return nodes.map((node) => ({
key: node.id,
title: node.name,
code: node.code,
type: node.type,
children: node.children && node.children.length > 0 ? toAntdTreeData(node.children) : undefined,
disabled: node.type === 'module',
}));
}
// 递归获取某节点下的所有叶子权限ID
function getLeafIds(nodes: PermissionVO.PermissionInfoVO[], parentId: number): number[] {
const result: number[] = [];
const children = nodes.find((n) => n.id === parentId)?.children;
if (!children) return [];
for (const child of children) {
if (child.type === 'module' && child.children) {
result.push(...getLeafIds(nodes, child.id));
} else {
result.push(child.id);
}
}
return result;
}
// 递归获取某节点的父节点链(从根到该节点)
function getParentChain(nodes: PermissionVO.PermissionInfoVO[], targetId: number, path: number[] = []): number[] {
for (const node of nodes) {
if (node.id === targetId) return [...path, node.id];
if (node.children) {
const found = getParentChain(node.children, targetId, [...path, node.id]);
if (found.length > 0) return found;
}
}
return [];
}
// Tree 勾选变化处理(支持父→子全选/取消,子→父自动勾选父节点)
function handleTreeCheck(checked: number[], info: any) {
const { node, checked: isChecked } = info;
const nodeId = node.key as number;
const nodeData = findNodeById(permissionTree.value, nodeId);
let newSelected = new Set(selectedPermissionIds.value);
if (isChecked) {
// 勾选:加入自己 + 所有子权限
newSelected.add(nodeId);
if (nodeData?.type !== 'module' && nodeData?.children) {
// 如果是子模块,展开时自动勾选所有叶子
const leafIds = getAllLeafIds([nodeData]);
leafIds.forEach((id) => newSelected.add(id));
}
// 自动勾选父节点链
const parents = getParentChain(permissionTree.value, nodeId);
parents.forEach((pid) => newSelected.add(pid));
} else {
// 取消勾选:移除自己 + 所有子权限
newSelected.delete(nodeId);
if (nodeData?.children) {
const leafIds = getAllLeafIds([nodeData]);
leafIds.forEach((id) => newSelected.delete(id));
}
// 不自动移除父节点(允许只选子节点)
}
selectedPermissionIds.value = Array.from(newSelected);
checkedKeys.value = [...newSelected];
}
// 递归查找节点
function findNodeById(nodes: PermissionVO.PermissionInfoVO[], id: number): PermissionVO.PermissionInfoVO | null {
for (const node of nodes) {
if (node.id === id) return node;
if (node.children) {
const found = findNodeById(node.children, id);
if (found) return found;
}
}
return null;
}
// 获取某节点下所有叶子权限ID
function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const result: number[] = [];
for (const node of nodes) {
if (node.type !== 'module' && !node.children) {
result.push(node.id);
} else if (node.children) {
result.push(...getAllLeafIds(node.children));
}
}
return result;
}
// 全选(只选叶子节点)
function selectAll() {
const allLeafIds = getAllLeafIds(permissionTree.value);
selectedPermissionIds.value = allLeafIds;
checkedKeys.value = [...allLeafIds];
}
// 取消全选
function selectNone() {
selectedPermissionIds.value = [];
checkedKeys.value = [];
}
onMounted(() => { onMounted(() => {
searchPositions(); searchPositions();
loadAllPermissions(); loadPermissionTree();
}); });
</script> </script>
@@ -197,14 +275,8 @@ onMounted(() => {
<Card <Card
title="职位列表" title="职位列表"
class="flex h-full max-w-[400px] flex-col" class="flex h-full max-w-[400px] flex-col"
:body-style="{ :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', gap: '10px' }"
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}"
> >
<!-- 搜索区域 -->
<Flex class="flex-wrap gap-2"> <Flex class="flex-wrap gap-2">
<Input <Input
v-model:value="searchForm.name" v-model:value="searchForm.name"
@@ -221,11 +293,10 @@ onMounted(() => {
<Select.Option :value="1">启用</Select.Option> <Select.Option :value="1">启用</Select.Option>
<Select.Option :value="0">禁用</Select.Option> <Select.Option :value="0">禁用</Select.Option>
</Select> </Select>
<Button type="primary" @click="searchPositions"> 搜索 </Button> <Button type="primary" @click="searchPositions">搜索</Button>
<Button @click="resetSearch"> 重置 </Button> <Button @click="resetSearch">重置</Button>
</Flex> </Flex>
<!-- 职位列表区域 -->
<Flex vertical class="flex-1"> <Flex vertical class="flex-1">
<Spin :spinning="positionLoading"> <Spin :spinning="positionLoading">
<div class="flex-1"> <div class="flex-1">
@@ -236,10 +307,7 @@ onMounted(() => {
size="small" size="small"
:body-style="{ padding: '10px 12px' }" :body-style="{ padding: '10px 12px' }"
class="group mb-2 cursor-pointer transition-all duration-200" class="group mb-2 cursor-pointer transition-all duration-200"
:class="[ :class="[currentPosition?.id === position.id && 'ring-primary shadow ring-1']"
currentPosition?.id === position.id &&
'ring-primary shadow ring-1',
]"
@click="selectPosition(position)" @click="selectPosition(position)"
> >
<div class="flex items-start justify-between gap-2"> <div class="flex items-start justify-between gap-2">
@@ -247,23 +315,14 @@ onMounted(() => {
<div class="mb-1 flex items-center gap-2"> <div class="mb-1 flex items-center gap-2">
<span <span
class="inline-block h-2 w-2 rounded-full" class="inline-block h-2 w-2 rounded-full"
:class=" :class="position.status === 1 ? 'bg-green-500' : 'bg-red-500'"
position.status === 1 ? 'bg-green-500' : 'bg-red-500'
"
></span> ></span>
<span <span class="truncate text-sm font-semibold text-[var(--text-primary)]">
class="truncate text-sm font-semibold text-[var(--text-primary)]"
>
{{ position.name }} {{ position.name }}
</span> </span>
</div> </div>
<div class="mb-1 text-xs text-[var(--text-secondary)]"> <div class="text-xs text-[var(--text-secondary)]">编码:{{ position.code }}</div>
编码:{{ position.code }} <div v-if="position.remark" class="truncate text-xs text-[var(--text-secondary)]">
</div>
<div
v-if="position.remark"
class="truncate text-xs text-[var(--text-secondary)]"
>
{{ position.remark }} {{ position.remark }}
</div> </div>
</div> </div>
@@ -275,7 +334,6 @@ onMounted(() => {
</div> </div>
</Spin> </Spin>
<!-- 分页器 -->
<Flex justify="center" class="mt-2"> <Flex justify="center" class="mt-2">
<Pagination <Pagination
v-model:current="positionPagination.current" v-model:current="positionPagination.current"
@@ -297,13 +355,11 @@ onMounted(() => {
:body-style="{ height: '100%' }" :body-style="{ height: '100%' }"
> >
<template v-if="currentPosition"> <template v-if="currentPosition">
<!-- 职位信息 + 统计与操作 --> <!-- 职位信息 + 操作 -->
<div class="mb-4 rounded bg-gray-50 p-4 dark:bg-neutral-800"> <div class="mb-4 rounded bg-gray-50 p-4 dark:bg-neutral-800">
<div class="mb-3 flex items-center justify-between gap-2"> <div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span class="text-base font-semibold">{{ <span class="text-base font-semibold">{{ currentPosition.name }}</span>
currentPosition.name
}}</span>
<Tag :color="currentPosition.status === 1 ? 'green' : 'red'"> <Tag :color="currentPosition.status === 1 ? 'green' : 'red'">
{{ currentPosition.status === 1 ? '启用' : '禁用' }} {{ currentPosition.status === 1 ? '启用' : '禁用' }}
</Tag> </Tag>
@@ -311,114 +367,76 @@ onMounted(() => {
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<Button @click="selectNone">取消全选</Button> <Button @click="selectNone">取消全选</Button>
<Button type="primary" @click="selectAll">一键全选</Button> <Button type="primary" @click="selectAll">一键全选</Button>
<Button <Button type="primary" :disabled="!stats.changed" @click="savePermissions">
type="primary"
:disabled="!stats.changed"
@click="savePermissions"
>
保存权限 保存权限
</Button> </Button>
</div> </div>
</div> </div>
<div class="flex items-center gap-6 text-xs text-gray-500"> <div class="flex items-center gap-6 text-xs text-gray-500">
<span>编码:{{ currentPosition.code }}</span> <span>编码:{{ currentPosition.code }}</span>
<span>全部叶子权限:<span class="font-semibold">{{ stats.total }}</span></span>
<span> <span>
全部权限:<span class="font-semibold">{{ stats.total }}</span> 已分配:<span class="font-semibold text-[var(--success)]">{{ stats.assigned }}</span>
</span>
<span>
已分配:<span class="font-semibold text-[var(--success)]">{{
stats.assigned
}}</span>
</span> </span>
<span> <span>
当前选择:<span 当前选择:<span
class="font-semibold" class="font-semibold"
:class=" :class="stats.changed ? 'text-[var(--warning)]' : 'text-[var(--success)]'"
stats.changed >
? 'text-[var(--warning)]' {{ stats.selected }}
: 'text-[var(--success)]'
"
>{{ stats.selected }}
</span> </span>
</span> </span>
<span v-if="stats.changed" class="text-[var(--warning)]"> <span v-if="stats.changed" class="text-[var(--warning)]">(有未保存的更改)</span>
(有未保存的更改) </div>
</span> <div class="mt-2 text-xs text-gray-400">
提示:勾选父节点会自动选中所有子权限;取消父节点会同时取消所有子权限
</div> </div>
</div> </div>
<!-- 权限列表 --> <!-- 权限树 -->
<div class="min-h-0 flex-1 overflow-y-auto"> <div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading"> <Spin :spinning="permissionLoading">
<div class="space-y-4"> <Tree
<div v-if="permissionTree.length > 0"
v-for="(permissions, type) in groupedPermissions" checkable
:key="type" :tree-data="toAntdTreeData(permissionTree)"
class="rounded border p-3" v-model:checked-keys="checkedKeys"
> :expanded-keys="permissionTree.map((n) => n.id)"
<div class="mb-2 text-sm font-semibold"> :auto-expand-parent="true"
{{ :selectable="false"
type === 'api' class="permission-tree"
? '接口权限' @check="(checked: number[], info: any) => handleTreeCheck(checked, info)"
: type === 'button' >
? '按钮权限' <template #title="{ dataRef }">
: type === 'data' <div class="flex items-center justify-between gap-4 pr-4">
? '数据权限' <div class="flex items-center gap-2">
: '其他权限' <span
}} :class="
<Tag class="ml-2" color="blue"> dataRef.type === 'module'
{{ permissions.length }} ? 'font-semibold text-[var(--text-primary)]'
</Tag> : 'text-[var(--text-secondary)]'
</div>
<div
class="grid grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-4"
>
<div
v-for="perm in permissions"
:key="perm.id"
class="flex items-center gap-2 rounded bg-white p-2 dark:bg-neutral-900"
>
<Checkbox
:checked="selectedPermissionIds.includes(perm.id)"
:disabled="perm.status !== 1"
@change="
(e: any) =>
togglePermission(perm.id, e.target.checked)
" "
> >
<div class="min-w-0"> {{ dataRef.title }}
<div </span>
class="truncate text-sm" <span class="text-xs text-gray-400">{{ dataRef.code }}</span>
:class="
perm.status !== 1
? 'text-gray-400'
: 'text-[var(--text-primary)]'
"
>
{{ perm.name }}
</div>
<div
class="truncate text-xs"
:class="
perm.status !== 1
? 'text-gray-300'
: 'text-[var(--text-secondary)]'
"
>
{{ perm.code }}
</div>
</div>
</Checkbox>
</div> </div>
<Tag
v-if="dataRef.type !== 'module'"
:color="
selectedPermissionIds.includes(dataRef.key as number)
? 'green'
: 'default'
"
class="text-xs"
>
{{ selectedPermissionIds.includes(dataRef.key as number) ? '已选' : '未选' }}
</Tag>
</div> </div>
</div> </template>
</Tree>
<div <div v-else-if="!permissionLoading" class="py-8 text-center text-gray-500">
v-if="allPermissions.length === 0" 暂无可分配的权限
class="py-8 text-center text-gray-500"
>
暂无可分配的权限
</div>
</div> </div>
</Spin> </Spin>
</div> </div>
@@ -1,87 +1,47 @@
<script setup lang="ts"> <script setup lang="ts">
import type { CompanyVO } from '#/api/organization/company/types'; import type { CompanyVO } from '#/api/organization/company/types';
import type { PermissionVO } from '#/api/system/permission/types';
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { import { Button, Card, Flex, Input, message, Pagination, Select, Spin, Tag, Tree } from 'ant-design-vue';
Button,
Card,
Checkbox,
Flex,
Input,
message,
Pagination,
Select,
Spin,
Tag,
} from 'ant-design-vue';
import { import { batchUpdateCompanyPermissionsApi, getCompanyPermissionIdsApi } from '#/api/organization/company-permission/apis';
batchUpdateCompanyPermissionsApi,
getCompanyPermissionIdsApi,
} from '#/api/organization/company-permission/apis';
import { getCompanyPageApi } from '#/api/organization/company'; import { getCompanyPageApi } from '#/api/organization/company';
import { getAllPermissionsApi } from '#/api/system/permission'; import { getPermissionTreeApi } from '#/api/system/permission';
defineOptions({ defineOptions({ name: 'CompanyPermissionManagePage' });
name: 'CompanyPermissionManagePage',
});
// 搜索表单 // 搜索表单
const searchForm = ref({ const searchForm = ref({ name: '', status: undefined as number | undefined });
name: '',
status: undefined as number | undefined,
});
// 公司列表 // 公司列表
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]); const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
const companyLoading = ref(false); const companyLoading = ref(false);
const companyPagination = ref({ const companyPagination = ref({ current: 1, pageSize: 10, total: 0 });
current: 1,
pageSize: 10,
total: 0,
});
// 当前选中的公司 // 当前选中的公司
const currentCompany = ref<null | CompanyVO.CompanyInfoVO>(null); const currentCompany = ref<null | CompanyVO.CompanyInfoVO>(null);
// 所有权限列表 // 权限树数据
const allPermissions = ref<any[]>([]); const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const permissionLoading = ref(false);
// 当前公司的权限ID列表 // 当前公司的权限ID
const companyPermissionIds = ref<number[]>([]); const companyPermissionIds = ref<number[]>([]);
const selectedPermissionIds = ref<number[]>([]); const selectedPermissionIds = ref<number[]>([]);
const checkedKeys = ref<number[]>([]);
// 权限加载状态
const permissionLoading = ref(false);
// 统计 // 统计
const stats = computed(() => ({ const stats = computed(() => ({
total: allPermissions.value.length, total: countLeafPermissions(permissionTree.value),
company: companyPermissionIds.value.length, company: companyPermissionIds.value.length,
selected: selectedPermissionIds.value.length, selected: selectedPermissionIds.value.length,
changed: selectedPermissionIds.value.length !== companyPermissionIds.value.length, changed: selectedPermissionIds.value.length !== companyPermissionIds.value.length,
})); }));
// 按类型分组
const groupedPermissions = computed(() => {
const groups: Record<string, any[]> = {};
for (const perm of allPermissions.value) {
const type = perm.type || 'other';
if (!groups[type]) groups[type] = [];
groups[type].push(perm);
}
return groups;
});
const typeLabelMap: Record<string, string> = {
api: '接口权限',
button: '按钮权限',
data: '数据权限',
};
// 搜索公司列表 // 搜索公司列表
async function searchCompanies() { async function searchCompanies() {
companyLoading.value = true; companyLoading.value = true;
@@ -89,10 +49,7 @@ async function searchCompanies() {
const result = await getCompanyPageApi({ const result = await getCompanyPageApi({
page: companyPagination.value.current, page: companyPagination.value.current,
pageSize: companyPagination.value.pageSize, pageSize: companyPagination.value.pageSize,
filters: { filters: { name: searchForm.value.name || undefined, status: searchForm.value.status },
name: searchForm.value.name || undefined,
status: searchForm.value.status,
},
}); });
companyList.value = result.records; companyList.value = result.records;
companyPagination.value.total = result.total; companyPagination.value.total = result.total;
@@ -109,19 +66,15 @@ async function selectCompany(company: CompanyVO.CompanyInfoVO) {
await loadCompanyPermissions(); await loadCompanyPermissions();
} }
// 加载当前公司的权限 // 加载公司权限
async function loadCompanyPermissions() { async function loadCompanyPermissions() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
permissionLoading.value = true; permissionLoading.value = true;
try { try {
const [perms, permIds] = await Promise.all([ const result = await getCompanyPermissionIdsApi(currentCompany.value.id);
getAllPermissionsApi(), companyPermissionIds.value = result || [];
getCompanyPermissionIdsApi(currentCompany.value.id),
]);
const permArray = Array.isArray(perms) ? perms : (perms?.data || []);
allPermissions.value = permArray.filter((p: any) => p.status === 1);
companyPermissionIds.value = permIds || [];
selectedPermissionIds.value = [...companyPermissionIds.value]; selectedPermissionIds.value = [...companyPermissionIds.value];
checkedKeys.value = [...companyPermissionIds.value];
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '加载权限失败'); message.error(error?.message || '加载权限失败');
} finally { } finally {
@@ -129,34 +82,21 @@ async function loadCompanyPermissions() {
} }
} }
// 切换单个权限 // 加载权限树
function togglePermission(permissionId: number, checked: boolean) { async function loadPermissionTree() {
if (checked) { try {
selectedPermissionIds.value.push(permissionId); const result = await getPermissionTreeApi();
} else { permissionTree.value = result.data || [];
selectedPermissionIds.value = selectedPermissionIds.value.filter( } catch (error: any) {
(id) => id !== permissionId, message.error(error?.message || '获取权限树失败');
);
} }
} }
// 全选/取消全选
function selectAll() {
selectedPermissionIds.value = allPermissions.value.map((p) => p.id);
}
function selectNone() {
selectedPermissionIds.value = [];
}
// 保存 // 保存
async function handleSave() { async function handleSave() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
try { try {
await batchUpdateCompanyPermissionsApi( await batchUpdateCompanyPermissionsApi(currentCompany.value.id, selectedPermissionIds.value);
currentCompany.value.id,
selectedPermissionIds.value,
);
message.success('权限配置保存成功'); message.success('权限配置保存成功');
companyPermissionIds.value = [...selectedPermissionIds.value]; companyPermissionIds.value = [...selectedPermissionIds.value];
} catch (error: any) { } catch (error: any) {
@@ -178,9 +118,103 @@ function handlePageChange(page: number, pageSize: number) {
searchCompanies(); searchCompanies();
} }
// 初始化 // 统计叶子权限数
function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number {
let count = 0;
for (const node of nodes) {
if (node.children && node.children.length > 0) count += countLeafPermissions(node.children);
else count++;
}
return count;
}
// 转 Ant Design Tree 格式
function toAntdTreeData(nodes: PermissionVO.PermissionInfoVO[]): any[] {
return nodes.map((node) => ({
key: node.id,
title: node.name,
code: node.code,
type: node.type,
children: node.children && node.children.length > 0 ? toAntdTreeData(node.children) : undefined,
disabled: node.type === 'module',
}));
}
// 递归获取某节点下所有叶子权限ID
function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const result: number[] = [];
for (const node of nodes) {
if (node.type !== 'module' && !node.children) result.push(node.id);
else if (node.children) result.push(...getAllLeafIds(node.children));
}
return result;
}
// 递归获取父节点链
function getParentChain(nodes: PermissionVO.PermissionInfoVO[], targetId: number, path: number[] = []): number[] {
for (const node of nodes) {
if (node.id === targetId) return [...path, node.id];
if (node.children) {
const found = getParentChain(node.children, targetId, [...path, node.id]);
if (found.length > 0) return found;
}
}
return [];
}
// 递归查找节点
function findNodeById(nodes: PermissionVO.PermissionInfoVO[], id: number): PermissionVO.PermissionInfoVO | null {
for (const node of nodes) {
if (node.id === id) return node;
if (node.children) {
const found = findNodeById(node.children, id);
if (found) return found;
}
}
return null;
}
// Tree 勾选变化
function handleTreeCheck(_checked: number[], info: any) {
const { node, checked: isChecked } = info;
const nodeId = node.key as number;
const nodeData = findNodeById(permissionTree.value, nodeId);
let newSelected = new Set(selectedPermissionIds.value);
if (isChecked) {
newSelected.add(nodeId);
if (nodeData?.type !== 'module' && nodeData?.children) {
getAllLeafIds([nodeData]).forEach((id) => newSelected.add(id));
}
// 自动勾选父节点链
getParentChain(permissionTree.value, nodeId).forEach((pid) => newSelected.add(pid));
} else {
newSelected.delete(nodeId);
if (nodeData?.children) {
getAllLeafIds([nodeData]).forEach((id) => newSelected.delete(id));
}
}
selectedPermissionIds.value = Array.from(newSelected);
checkedKeys.value = [...newSelected];
}
// 全选 / 取消全选
function selectAll() {
const allLeafIds = getAllLeafIds(permissionTree.value);
selectedPermissionIds.value = allLeafIds;
checkedKeys.value = [...allLeafIds];
}
function selectNone() {
selectedPermissionIds.value = [];
checkedKeys.value = [];
}
onMounted(() => { onMounted(() => {
searchCompanies(); searchCompanies();
loadPermissionTree();
}); });
</script> </script>
@@ -191,14 +225,8 @@ onMounted(() => {
<Card <Card
title="公司列表" title="公司列表"
class="flex h-full max-w-[400px] flex-col" class="flex h-full max-w-[400px] flex-col"
:body-style="{ :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', gap: '10px' }"
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}"
> >
<!-- 搜索区域 -->
<Flex class="flex-wrap gap-2"> <Flex class="flex-wrap gap-2">
<Input <Input
v-model:value="searchForm.name" v-model:value="searchForm.name"
@@ -219,7 +247,6 @@ onMounted(() => {
<Button @click="resetSearch">重置</Button> <Button @click="resetSearch">重置</Button>
</Flex> </Flex>
<!-- 公司列表 -->
<Flex vertical class="flex-1 overflow-y-auto"> <Flex vertical class="flex-1 overflow-y-auto">
<Spin :spinning="companyLoading"> <Spin :spinning="companyLoading">
<Card <Card
@@ -229,10 +256,7 @@ onMounted(() => {
size="small" size="small"
:body-style="{ padding: '10px 12px' }" :body-style="{ padding: '10px 12px' }"
class="mb-2 cursor-pointer transition-all duration-200" class="mb-2 cursor-pointer transition-all duration-200"
:class="[ :class="[currentCompany?.id === company.id && 'ring-primary shadow ring-1']"
currentCompany?.id === company.id &&
'ring-primary shadow ring-1',
]"
@click="selectCompany(company)" @click="selectCompany(company)"
> >
<div class="flex items-start justify-between gap-2"> <div class="flex items-start justify-between gap-2">
@@ -285,67 +309,71 @@ onMounted(() => {
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<Button @click="selectNone">取消全选</Button> <Button @click="selectNone">取消全选</Button>
<Button type="primary" @click="selectAll">一键全选</Button> <Button type="primary" @click="selectAll">一键全选</Button>
<Button <Button type="primary" :disabled="!stats.changed" @click="handleSave">
type="primary"
:disabled="!stats.changed"
@click="handleSave"
>
保存配置 保存配置
</Button> </Button>
</div> </div>
</div> </div>
<div class="flex gap-6 text-xs text-gray-500"> <div class="flex gap-6 text-xs text-gray-500">
<span>全部权限:<strong>{{ stats.total }}</strong></span> <span>全部叶子权限:<strong>{{ stats.total }}</strong></span>
<span>已配置:<strong class="text-green-600">{{ stats.company }}</strong></span> <span>已配置:<strong class="text-green-600">{{ stats.company }}</strong></span>
<span>当前选择:<strong class="text-blue-600">{{ stats.selected }}</strong></span> <span>当前选择:<strong class="text-blue-600">{{ stats.selected }}</strong></span>
<span v-if="stats.changed" class="text-orange-500">(有未保存的更改)</span> <span v-if="stats.changed" class="text-orange-500">(有未保存的更改)</span>
</div> </div>
<div class="mt-2 text-xs text-gray-400">
提示:勾选父节点会自动选中所有子权限
</div>
</div> </div>
<!-- 权限列表 --> <!-- 权限树 -->
<div class="flex-1 overflow-y-auto"> <div class="flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading"> <Spin :spinning="permissionLoading">
<div class="space-y-4"> <Tree
<div v-if="permissionTree.length > 0"
v-for="(perms, type) in groupedPermissions" checkable
:key="type" :tree-data="toAntdTreeData(permissionTree)"
class="rounded border p-3" v-model:checked-keys="checkedKeys"
> :expanded-keys="permissionTree.map((n) => n.id)"
<div class="mb-3 text-sm font-semibold"> :auto-expand-parent="true"
{{ typeLabelMap[type] || type }} :selectable="false"
<Tag class="ml-2" color="blue">{{ perms.length }}</Tag> class="permission-tree"
</div> @check="(checked: number[], info: any) => handleTreeCheck(checked, info)"
<div class="grid grid-cols-2 gap-2 lg:grid-cols-3"> >
<div <template #title="{ dataRef }">
v-for="perm in perms" <div class="flex items-center justify-between gap-4 pr-4">
:key="perm.id" <div class="flex items-center gap-2">
class="flex items-center gap-2 rounded bg-white p-2 dark:bg-neutral-900" <span
> :class="
<Checkbox dataRef.type === 'module'
:checked="selectedPermissionIds.includes(perm.id)" ? 'font-semibold text-[var(--text-primary)]'
@change="(e: any) => togglePermission(perm.id, e.target.checked)" : 'text-[var(--text-secondary)]'
"
> >
<div class="min-w-0"> {{ dataRef.title }}
<div class="truncate text-sm">{{ perm.name }}</div> </span>
<div class="truncate text-xs text-gray-400">{{ perm.code }}</div> <span class="text-xs text-gray-400">{{ dataRef.code }}</span>
</div>
</Checkbox>
</div> </div>
<Tag
v-if="dataRef.type !== 'module'"
:color="selectedPermissionIds.includes(dataRef.key as number) ? 'green' : 'default'"
class="text-xs"
>
{{ selectedPermissionIds.includes(dataRef.key as number) ? '已选' : '未选' }}
</Tag>
</div> </div>
</div> </template>
</Tree>
<div <div v-else-if="!permissionLoading" class="py-8 text-center text-gray-400">
v-if="allPermissions.length === 0 && !permissionLoading" 暂无可分配的权限
class="py-8 text-center text-gray-400"
>
暂无可分配的权限
</div>
</div> </div>
</Spin> </Spin>
</div> </div>
</template> </template>
<div v-else class="flex h-full flex-1 items-center justify-center text-gray-400"> <div
v-else
class="flex h-full flex-1 items-center justify-center text-gray-400"
>
<div class="text-center"> <div class="text-center">
<div class="mb-2 text-5xl">👈</div> <div class="mb-2 text-5xl">👈</div>
<div>请先选择一家公司</div> <div>请先选择一家公司</div>
@@ -1,19 +1,21 @@
<script lang="ts" setup> <script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PermissionDTO, PermissionVO } from '#/api/system/permission'; import type { PermissionDTO, PermissionVO } from '#/api/system/permission';
import type { PageQueryDTO } from '#/types/common'; import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { computed, ref, onMounted } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue'; import { Button, message, Popconfirm, Space, Tag, Spin, Tree } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { import {
deletePermissionApi, deletePermissionApi,
getAllPermissionsApi,
getPermissionPageApi, getPermissionPageApi,
getPermissionTreeApi,
} from '#/api/system/permission'; } from '#/api/system/permission';
import PermissionFormModal from './components/PermissionFormModal.vue'; import PermissionFormModal from './components/PermissionFormModal.vue';
@@ -26,6 +28,12 @@ const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据 // 响应式数据
const loading = ref(false); const loading = ref(false);
const permissionFormModalRef = ref(); const permissionFormModalRef = ref();
const viewMode = ref<'table' | 'tree'>('table');
// 树数据
const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const treeLoading = ref(false);
const expandedKeys = ref<number[]>([]);
// 搜索表单 // 搜索表单
const searchForm = ref({ const searchForm = ref({
@@ -46,6 +54,7 @@ const typeOptions = [
{ label: '接口权限', value: 'api' }, { label: '接口权限', value: 'api' },
{ label: '按钮权限', value: 'button' }, { label: '按钮权限', value: 'button' },
{ label: '数据权限', value: 'data' }, { label: '数据权限', value: 'data' },
{ label: '模块', value: 'module' },
]; ];
// 搜索表单配置 // 搜索表单配置
@@ -119,6 +128,11 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 200, minWidth: 200,
showOverflow: 'tooltip' as const, showOverflow: 'tooltip' as const,
}, },
{
field: 'sortOrder',
title: '排序',
minWidth: 80,
},
{ {
field: 'createTime', field: 'createTime',
title: '创建时间', title: '创建时间',
@@ -166,7 +180,6 @@ const gridOptions: VxeGridProps<any> = {
| 'Total' | 'Total'
)[], )[],
}, },
// 配置远程加载
proxyConfig: { proxyConfig: {
ajax: { ajax: {
query: async ({ page }) => { query: async ({ page }) => {
@@ -187,10 +200,7 @@ const gridOptions: VxeGridProps<any> = {
const errorMessage = const errorMessage =
error?.response?.data?.message || error?.message || '查询数据失败'; error?.response?.data?.message || error?.message || '查询数据失败';
message.error(errorMessage); message.error(errorMessage);
return { return { items: [], total: 0 };
items: [],
total: 0,
};
} finally { } finally {
loading.value = false; loading.value = false;
} }
@@ -215,89 +225,112 @@ const hasSelected = computed(() => {
// 刷新表格数据 // 刷新表格数据
function refreshTable() { function refreshTable() {
if (gridApi) { if (gridApi) gridApi.reload();
gridApi.reload(); }
// 加载权限树
async function loadPermissionTree() {
treeLoading.value = true;
try {
const result = await getPermissionTreeApi();
permissionTree.value = result.data || [];
// 默认展开所有节点
expandedKeys.value = permissionTree.value.map((n) => n.id);
} catch (error: any) {
message.error(error?.message || '获取权限树失败');
} finally {
treeLoading.value = false;
} }
} }
const handleAdd = () => { // 切换视图
function switchView(mode: 'table' | 'tree') {
viewMode.value = mode;
if (mode === 'tree') loadPermissionTree();
}
function handleAdd() {
permissionFormModalRef.value?.open(); permissionFormModalRef.value?.open();
}; }
const handleEdit = (row: PermissionVO.PermissionInfoVO) => { function handleEdit(row: PermissionVO.PermissionInfoVO) {
permissionFormModalRef.value?.open(row); permissionFormModalRef.value?.open(row);
}; }
const handleDelete = async (row: PermissionVO.PermissionInfoVO) => { async function handleDelete(row: PermissionVO.PermissionInfoVO) {
try { try {
await deletePermissionApi(row.id); await deletePermissionApi(row.id);
message.success('删除成功'); message.success('删除成功');
refreshTable(); if (viewMode.value === 'tree') loadPermissionTree();
else refreshTable();
} catch (error: any) { } catch (error: any) {
console.error('删除失败:', error); message.error(error?.response?.data?.message || error?.message || '删除失败');
const errorMessage =
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
} }
}; }
const handleBatchDelete = async () => { async function handleBatchDelete() {
const vxeTable = (gridApi as any).grid; const vxeTable = (gridApi as any).grid;
const selectedRows = vxeTable?.getCheckboxRecords?.(); const selectedRows = vxeTable?.getCheckboxRecords?.();
if (!selectedRows?.length) { if (!selectedRows?.length) {
message.warning('请选择要删除的数据'); message.warning('请选择要删除的数据');
return; return;
} }
try { try {
const deletePromises = selectedRows.map( await Promise.all(selectedRows.map((row: PermissionVO.PermissionInfoVO) => deletePermissionApi(row.id)));
(row: PermissionVO.PermissionInfoVO) => deletePermissionApi(row.id),
);
await Promise.all(deletePromises);
message.success(`成功删除 ${selectedRows.length} 条记录`); message.success(`成功删除 ${selectedRows.length} 条记录`);
refreshTable(); refreshTable();
} catch (error: any) { } catch (error: any) {
console.error('批量删除失败:', error); message.error(error?.response?.data?.message || error?.message || '批量删除失败');
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
} }
};
// 处理模态框成功回调
function handleModalSuccess() {
refreshTable();
} }
// 获取权限类型文本 function handleModalSuccess() {
if (viewMode.value === 'tree') loadPermissionTree();
else refreshTable();
}
// 类型文本
const getTypeText = (type: string) => { const getTypeText = (type: string) => {
const typeMap = { const typeMap: Record<string, string> = {
api: '接口权限', api: '接口权限',
button: '按钮权限', button: '按钮权限',
data: '数据权限', data: '数据权限',
module: '模块分组',
}; };
return typeMap[type as keyof typeof typeMap] || type; return typeMap[type] || type;
}; };
// 获取权限类型颜色
const getTypeColor = (type: string) => { const getTypeColor = (type: string) => {
const colorMap = { const colorMap: Record<string, string> = {
api: 'blue', api: 'blue',
button: 'green', button: 'green',
data: 'orange', data: 'orange',
module: 'purple',
}; };
return colorMap[type as keyof typeof colorMap] || 'default'; return colorMap[type] || 'default';
}; };
// 获取状态文本 // Ant Design Tree 格式转换
const getStatusText = (status: number) => { function toAntdTreeData(nodes: PermissionVO.PermissionInfoVO[]): any[] {
return status === 1 ? '启用' : '禁用'; return nodes.map((node) => ({
}; key: node.id,
title: (
<span class="flex items-center gap-2">
<span class="font-medium">{node.name}</span>
<span class="text-xs text-gray-400">({node.code})</span>
<Tag color={node.status === 1 ? 'green' : 'red'} class="text-xs">
{node.status === 1 ? '启用' : '禁用'}
</Tag>
</span>
),
children: node.children ? toAntdTreeData(node.children) : undefined,
disabled: node.type === 'module',
}));
}
// 获取状态颜色 onMounted(() => {
const getStatusColor = (status: number) => { if (viewMode.value === 'tree') loadPermissionTree();
return status === 1 ? 'green' : 'red'; });
};
</script> </script>
<template> <template>
@@ -308,9 +341,20 @@ const getStatusColor = (status: number) => {
</div> </div>
</template> </template>
<!-- VbenVxeGrid 表格 --> <!-- 视图切换 -->
<Grid :loading="loading"> <div class="mb-4 flex items-center gap-3">
<!-- 工具栏工具 --> <Space>
<Button :type="viewMode === 'table' ? 'primary' : 'default'" @click="switchView('table')">
表格视图
</Button>
<Button :type="viewMode === 'tree' ? 'primary' : 'default'" @click="switchView('tree')">
树状视图
</Button>
</Space>
</div>
<!-- 表格视图 -->
<Grid v-if="viewMode === 'table'" :loading="loading">
<template #toolbar-tools> <template #toolbar-tools>
<Space> <Space>
<Button type="primary" @click="handleAdd"> <Button type="primary" @click="handleAdd">
@@ -323,34 +367,82 @@ const getStatusColor = (status: number) => {
</Space> </Space>
</template> </template>
<!-- 权限类型列 -->
<template #type="{ row }"> <template #type="{ row }">
<Tag :color="getTypeColor(row.type)"> <Tag :color="getTypeColor(row.type)">
{{ getTypeText(row.type) }} {{ getTypeText(row.type) }}
</Tag> </Tag>
</template> </template>
<!-- 状态列 -->
<template #status="{ row }"> <template #status="{ row }">
<Tag :color="getStatusColor(row.status)"> <Tag :color="row.status === 1 ? 'green' : 'red'">
{{ getStatusText(row.status) }} {{ row.status === 1 ? '启用' : '禁用' }}
</Tag> </Tag>
</template> </template>
<!-- 操作列 -->
<template #action="{ row }"> <template #action="{ row }">
<Space> <Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button> <Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm <Popconfirm title="确定要删除这个权限吗?" @confirm="handleDelete(row)">
title="确定要删除这个权限吗?" <Button size="small" danger>删除</Button>
@confirm="handleDelete(row)"
>
<Button size="small" danger> 删除 </Button>
</Popconfirm> </Popconfirm>
</Space> </Space>
</template> </template>
</Grid> </Grid>
<!-- 树状视图 -->
<div v-if="viewMode === 'tree'" class="rounded border bg-white p-4 dark:bg-neutral-800">
<div class="mb-3 flex items-center justify-between">
<span class="text-sm text-gray-500">权限树(共 {{ permissionTree.length }} 个顶级模块)</span>
<Button size="small" @click="handleAdd">添加权限</Button>
</div>
<Spin :spinning="treeLoading">
<Tree
v-if="permissionTree.length > 0"
:tree-data="toAntdTreeData(permissionTree)"
:expanded-keys="expandedKeys"
:selectable="false"
class="min-h-[400px]"
>
<template #title="{ key, dataRef }">
<div class="flex items-center justify-between gap-4 pr-4">
<div class="flex items-center gap-2">
<span class="font-medium">{{ dataRef.name }}</span>
<span class="text-xs text-gray-400">{{ dataRef.code }}</span>
</div>
<Space size="small">
<Tag :color="getTypeColor(dataRef.type)" class="text-xs">
{{ getTypeText(dataRef.type) }}
</Tag>
<Tag :color="dataRef.status === 1 ? 'green' : 'red'" class="text-xs">
{{ dataRef.status === 1 ? '启用' : '禁用' }}
</Tag>
<Button
v-if="dataRef.type !== 'module'"
size="small"
type="text"
@click.stop="handleEdit(dataRef)"
>
编辑
</Button>
<Popconfirm
v-if="dataRef.type !== 'module'"
title="确定要删除这个权限吗?"
@confirm="handleDelete(dataRef)"
>
<Button size="small" type="text" danger @click.stop>
删除
</Button>
</Popconfirm>
</Space>
</div>
</template>
</Tree>
<div v-else-if="!treeLoading" class="py-8 text-center text-gray-400">
暂无权限数据
</div>
</Spin>
</div>
<!-- 权限表单弹窗 --> <!-- 权限表单弹窗 -->
<PermissionFormModal <PermissionFormModal
ref="permissionFormModalRef" ref="permissionFormModalRef"