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
@@ -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>