给角色修改权限的时候 - 后台管理系统
点击修改按钮:定于一个修改的方法,调出弹出层 ;
async editRow(id) { // 获取详细信息 当前修改的角色信息 @lcick row.id const res = await getRoleInfoApi(id); // 弹框打开 推荐先赋值回显数据 然后打开弹窗 this.$refs.addRole.dialogShow = true; // 赋给表单的formData 回显数据 this.$refs.addRole.formData = res; // 获取叶子上面的节点ID 树 tree 怎么回显,包含半钩和全钩 注意:只需要找到tree的数据的最深层的数据即可 const menuSmallId = []; res.authList.forEach((item) => { this.getDefaultCheck(item, menuSmallId); }); this.$refs.addRole.defaultCheckKeys = menuSmallId; },
递归函数获取最深层的选中数据 ;
// 获取叶子上面的节点ID getDefaultCheck(node, arr) { // node是节点信息,arr是存储数组 if (node.children && node.children.length) { node.children.forEach((val) => { this.getDefaultCheck(val, arr); }); } else { return arr.push(node.id); } },
弹层:
<template> <!-- 弹框 --> <el-dialog title="添加角色" :visible.sync="dialogShow" width="40%" @close="closeDialog" > <!-- 表单 --> <el-form :model="formData" ref="formRef" :rules="formRules" label-width="90px" :inline="false" size="noraml" > <el-form-item label="角色名称" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> <el-form-item label="角色描述" prop="description"> <el-input v-model="formData.description"></el-input> </el-form-item> <el-form-item label="权限"> <!-- 展示树 --> <el-tree ref="tree" :data="allAuth" show-checkbox :props="{ label: 'title' }" node-key="id" :default-checked-keys="defaultCheckKeys" ></el-tree> </el-form-item> </el-form> <span slot="footer"> <el-button size="small" @click="dialogShow = false">取消</el-button> <el-button size="small" @click="btnOK" type="primary">确定</el-button> </span> </el-dialog> </template> <script> import { addRoleApi, editRoleApi } from '@/api/Role'; import { getMenuListApi } from '@/api/Menu'; export default { name: 'AddRole', data() { return { dialogShow: false, formData: { name: '', description: '', menuids: [], // 获取所有打钩的或半钩的数据 }, formRules: { name: [{ required: true, message: '请输入', trigger: 'blur' }], description: [{ required: true, message: '请输入', trigger: 'blur' }], }, allAuth: [], defaultCheckKeys: [], }; }, mounted() { this.getAllMenu(); }, methods: { // 获取到所有权限 async getAllMenu() { let res = await getMenuListApi(); this.allAuth = res; }, closeDialog() { this.formData = { tagname: '', }; this.defaultCheckKeys = []; this.$refs.formRef.resetFields(); }, async btnOK() { try { await this.$refs.formRef.validate(); } catch (error) { return console.log(error); } // 发生请求 const checkKeys = this.$refs.tree.getCheckedKeys(); // 对钩 const halfKeys = this.$refs.tree.getHalfCheckedKeys(); // 半钩 this.formData.menuids = [...checkKeys, ...halfKeys]; // 整理数据 if (this.formData.id) { await editRoleApi(this.formData); } else { await addRoleApi(this.formData); } this.$emit('updateList'); this.$message.success('新增成功'); this.dialogShow = false; }, }, }; </script> <style lang="scss" scoped></style>
回显数据的核心: :default-checked-keys="defaultCheckKeys" 默认选中的tree选项 ;