前言
在为角色配置权限菜单时,采用树结构时,对选中的多选框获取,和已配菜单的默认选中操作。
(不想看过程的可以直接到总结里查看具体调用方法)
一、所用数据
1、树结构
(这里用了有名的pug插件,省去了结束标签方便开发,
show-checkbox显示多选框;
:data="menuData"获取树数据;
node-key="idMenu"关键属性,必填;
:props="defaultProps"自定义树结构,官方默认结构可以不写;
ref="tree"获取树响应的数据,也是本篇文章的关键属性;
default-expand-all默认全部展开;
|符:pug里的关键符,等于标签体内容)
<template lang="pug">
...
el-dialog(title="配置菜单" v-model="roleVisible2" :before-close="roleClose2" )
el-tree(
show-checkbox
:data="menuData"
node-key="idMenu"
:props="defaultProps"
ref="tree"
default-expand-all
)
template(#default="{ node, data }")
span
| {{ data.menuName }}
template(#footer)
el-button(@click="roleClose2") 取消
el-button(type="primary" @click="submitRole2" :loading="dataLoading2") 确定
</template>
1、data
(Options类语法风格的组件,setup风格的需进行转换)
data() {
const menuData: Menu[] = [];
return {
menuData,
//状态属性
roleVisible: false,
roleVisible2: false,
dataLoading: false,
dataLoading2: false,
//表单属性
formTitle: "角色管理",
roleForm: {},
//树结构
defaultProps: {
children: "childList",
label: "menuName",
},
idRole: "",
setMenuData: [],
};
},
3、方法
mounted() {
this.getMenuData();
},
methods: {
//获取全部目录
async getMenuData() {
await api.menu.getMenuAll().then((data) => {
this.menuData = data;
});
},
//获取选中角色目录
async getByIdRole() {
await api.menu.getByIdRole(this.idRole).then((data) => {
this.setMenuData = data;
this.getTreeSelection(this.setMenuData);
});
},
//打开操作框
roleManage(key: string, data?: Role) {
switch (key) {
...
case "configure":
this.idRole = (data as Role).idRole;
this.roleVisible2 = true;
if (!this.menuData[0]) this.getByIdRole();
break;
}
},
//保存修改
submitRole2() {
this.dataLoading2 = true;
const getIdMenus: string[] = [];
//获取选中的多选框
const res = this.$refs.tree.getCheckedNodes();
if (res.length > 0) {
console.log(res);
res.forEach((item: Menu) => {
getIdMenus.push(item.idMenu);
});
const entity = {
idRole: this.idRole,
getIdMenus,
};
try {
api.menu.setForRole(entity);
this.roleVisible2 = false;
setTimeout(() => {
ElMessage.success("配置成功");
// location.reload();
}, 1500);
} catch (error) {
ElMessage("操作失败");
}
}
this.dataLoading2 = false;
},
//获取树结构选中数组
getTreeSelection(data: object[]) {
const setIdMenus: string[] = [];
for (let i = 0; i < data.length; i++) {
if (data[i].children) {
this.getTreeSelection(data[i].children);
} else {
setIdMenus.push(data[i].idMenu);
}
}
this.$refs.tree.setCheckedKeys(setIdMenus);
},
}
总结
本篇主要是在tree结构里用ref绑定的属性,然后调用它的两个方法:
//获取选中多选框
const res = this.$refs.tree.getCheckedNodes();
//默认选中
const setIdMenus: string[] = [];
this.$refs.tree.setCheckedKeys(setIdMenus);
实现set和get功能。
以上就是今天要讲的内容,感谢大家观看。