我的需求是修改角色的权限,需要一个树形多选框来展示权限信息,并修改
用一个模态框包着一个树形组件
<el-dialog v-model="treeDialog.visible" :title="treeDialog.title">
<el-tree
ref="treeRef"
class="tree-border"
:data="menuOptions"
show-checkbox
node-key="id"
empty-text="加载中,请稍候"
:props="{ label: 'label', children: 'children' }"
:default-checked-keys="checkKeys"
accordion
></el-tree>
<el-button @click="getCheckedKeys">确认</el-button>
</el-dialog>
:default-checked-keys="checkKeys"是为了让默认显示,比如后端通过id获取已有的权限,就可以默认选中了
可以通过treeRef的属性来获取和设置选中的值,下面是官网的图解(部分)
我采用前后端分离来实现数据显示,后端用的是Java,这里用模拟数据来替换
// 一定要给treeRef赋值成空,反正我用了官网示例那个赋值,bug下拉,没找的问题
const treeRef = ref([]);
const menuOptions = [
{
id: 1,
label: "系统管理",
children: [
{
id: 101,
label: "用户管理",
children: [
{
id: 1001,
label: "查看用户",
children: [],
},
{
id: 1002,
label: "编辑用户",
children: [],
},
{
id: 1003,
label: "新增用户",
children: [],
},
{
id: 1004,
label: "删除用户",
children: [],
},
],
},
{
id: 102,
label: "角色管理",
children: [
{
id: 1005,
label: "查看角色",
children: [],
},
{
id: 1006,
label: "编辑角色",
children: [],
},
{
id: 1007,
label: "新增角色",
children: [],
},
{
id: 1008,
label: "删除角色",
children: [],
},
],
},
{
id: 103,
label: "菜单管理",
children: [
{
id: 1009,
label: "查看菜单",
children: [],
},
{
id: 1010,
label: "编辑菜单",
children: [],
},
{
id: 1011,
label: "新增菜单",
children: [],
},
{
id: 1012,
label: "删除菜单",
children: [],
},
],
},
{
id: 104,
label: "字典管理",
children: [],
},
{
id: 105,
label: "通知公告",
children: [],
},
],
},
{
id: 2,
label: "系统监控",
children: [
{
id: 106,
label: "在线用户",
children: [],
},
{
id: 107,
label: "数据监控",
children: [],
},
{
id: 108,
label: "服务监控",
children: [],
},
{
id: 109,
label: "缓存监控",
children: [],
},
{
id: 110,
label: "缓存列表",
children: [],
},
],
},
{
id: 3,
label: "文章管理",
children: [
{
id: 111,
label: "文章列表",
children: [],
},
{
id: 112,
label: "发布文章",
children: [],
},
{
id: 113,
label: "标签管理",
children: [],
},
{
id: 114,
label: "分类管理",
children: [],
},
],
},
{
id: 4,
label: "日志管理",
children: [
{
id: 115,
label: "操作日志",
children: [],
},
{
id: 116,
label: "登录日志",
children: [],
},
],
},
{
id: 5,
label: "测试图标",
children: [
{
id: 117,
label: "测试",
children: [],
},
{
id: 118,
label: "测试1",
children: [],
},
],
},
];
下面写一下后端获取逻辑
<script setup lang="ts">
const checkKeys = ref<number[]>();// 默认选中数组
const menuOptions = ref(); // 封装权限Tree数据
// 模态框数据
const treeDialog = reactive({
title: "授予权限",
visible: false,
});
// 后端交互逻辑 比如open就是一个按钮的@click=open 吧
function open() {
// 从后端获取数据,获取的数据就是上面给出的模拟数据
getMenuOptions().then(({ data }) => {
menuOptions.value = data;
treeDialog.visible = true;
treeDialog.title = "授予权限";
});
// 获取该role拥有的权限, 后端封装的结果是一个Long数组 我后端是将权限的id封装起来
// 比如 Long[] RoleArray = {1L,2L,3L,4L}; 前端拿到的其实就是 [1,2,3,4]
getRolePerm(roleId).then(({data}) => {
checkKeys.value = data;
})
}
</script>