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