05-权限列表

权限列表

1 通过路由的形式展示权限列表
  1. 首先在components文件夹下新建power文件夹 新建Right和Role组件

步骤同新建用户列表的User组件

  1. 在路由文件中导入新建的两个权限列表组件 在home路由规则中添加子路由
 { path: '/home', component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles }
    ] }
  1. 解决element-ui单一路由重复点击报错问题
// 解决重复点击某个路由报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/CmPFg2OHYZBj.png

2 权限列表之Rights组件
  1. 绘制Rights组件UI–面包屑导航+卡片视图+表单+标签
  2. 调用api获取数据
// 获取权限数据
      async getRightsList() {
        const {data: res} = await this.$http.get('rights/list');
        if (res.meta.status !== 200) {
            return this.$message.error('获取权限数据失败!');
        }
        // 为权限数据列表赋值
        this.rightsList = res.data;
      }
    }

在页面加载时立即调用

   created() {
      // 在页面加载的时候立即获取权限数据
      this.getRightsList();
   }
  1. 渲染Rights组件-三个if判断是哪一级的权限
<!--      面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>权限列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--      卡片视图-->
      <el-card>
        <el-table :data="rightsList" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="权限名称" prop="authName"></el-table-column>
          <el-table-column label="路径" prop="path"></el-table-column>
          <el-table-column label="权限等级" prop="level"></el-table-column>
          <el-table-column label="权限名称" prop="authName">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.level === '0'">一级权限</el-tag>
              <el-tag v-else-if="scope.row.level === '1'" type="success">二级权限</el-tag>
              <el-tag v-else type="warning">三级权限</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
3 权限列表之Roles组件
  1. 绘制Roles组件UI–面包屑导航+卡片视图+按钮+表单+对话框
  2. 获取并渲染角色列表数据
  • 首先在data中定义所有角色的数据列表 roleList
  • 调用api获取所有角色的数据列表
  // 获取角色列表信息
    async getRolesList() {
      const {data: res} = await this.$http.get('roles');
      if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表信息失败!');
      }
      // 为角色信息列表赋值
      this.roleList = res.data;
      this.$message.success('获取角色列表信息成功!');
    }
  • 在页面加载时立即调用
  created() {
    this.getRolesList();
  }
  • 渲染角色数据
<!--        角色列表区域-->
        <el-table :data="roleList" border stripe>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showEditRolesDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button @click="removeRolesById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/FfI2At4mWoZt.png

  • 渲染角色下权限

添加展开列和element标签组件通过三重for循环渲染权限标签 数据由作用域插槽获取

<!--          展开列-->
          <el-table-column label="展开" type="expand">
            <template slot-scope="scope">
              <el-row :class="['vcenter', 'bdbottom', i1 === 0 ? 'bdtop' : '']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
<!--                渲染一级权限-->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
<!--                渲染二级和三级权限-->
                <el-col :span="19">
                  <el-row :class="['vcenter', i2 === 0 ? '' : 'bdtop']" v-for="(item2, i2) in item1.children" :key="item2.id">
<!--                    渲染二级权限-->
                    <el-col :span="6">
                      <el-tag closable @close="removeRightById(scope.row, item2.id)" type="success">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
<!--                    渲染三级权限-->
                    <el-col :span="18">
                      <el-tag closable @close="removeRightById(scope.row, item3.id)" type="warning" v-for="(item3, i3) in item2.children" :key="item3.id">
                        {{item3.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/z1ka!OHwpKEo.png

  • 删除角色下的权限

给每个权限添加removeRightById事件处理函数 将作用域插槽数据scope.row和权限id传进去

      // 根据id删除对应权限
    async removeRightById(role, rightId) {
        // 弹框询问是否删除权限
        const confirmResult = await this.$confirm('此操作将永久删除该角色权限,是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => {
            return err;
        });
        if (confirmResult !== 'confirm') {
            return this.$message.info('您取消了删除操作');
        }
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
        if (res.meta.status !== 200) {
            return this.$message.error('权限删除失败!');
        }
        // this.getRolesList();
        role.children = res.data;
    }

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/oRkNX6SgJQqi.png
3. 增加、修改和删除角色

原理与User组件增加用户、修改用户和删除用户相同

增加角色对话框

<!--      添加角色对话框-->
      <el-dialog
        @close="addRolesDialogClosed"
        title="添加角色"
        :visible.sync="addRolesDialogVisible"
        width="50%">
        <!--        内容主题区域-->
        <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/Abgds4KHxeYE.png
修改角色对话框

 <!--      修改角色对话框-->
      <el-dialog
        @close="editRolesDialogClosed"
        title="修改角色"
        :visible.sync="editRolesDialogVisible"
        width="50%">
        <!--        内容主题区域-->
        <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesInfo">确 定</el-button>
        </span>
      </el-dialog>

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/z1uA*detGIza.png
事件处理函数

增加角色

 // 添加角色列表
    addRoles() {
      // 表单预校验
      this.$refs.addRolesFormRef.validate(async valid => {
          if (!valid) return;
          // 通过预校验则发起请求
          const {data: res} = await this.$http.post('roles', this.addRolesForm);
          if (res.meta.status !== 201) {
              return this.$message.error('添加角色失败!');
          }
          // console.log(res.data);
          // 关闭添加用户对话框
          this.addRolesDialogVisible = false;
          // 重新获取角色列表信息
          this.getRolesList();
          this.$message.success('添加角色成功!');
      })
    }

修改角色

    editRolesInfo() {
        // 表单预校验
      this.$refs.editRolesFormRef.validate(async valid =>{
          if (!valid) return;
          // 通过预校验则发起请求
          const {data: res} = await this.$http.put('roles/' + this.editRolesForm.roleId, {
              roleName: this.editRolesForm.roleName,
              roleDesc: this.editRolesForm.roleDesc
          });
          if (res.meta.status !== 200) {
              return this.$message.error('修改角色信息失败!');
          }
          this.$message.success('修改角色信息成功!');
          // 修改成功关闭对话框
          this.editRolesDialogVisible = false;
          // 重新获取角色信息列表
          this.getRolesList();
      })
    }

删除角色

  async removeRolesById(id) {
        // 弹框询问是否删除角色
        const confirmResult = await this.$confirm('此操作将永久删除该角色,是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => {
            return err;
        });
        // 如果用户确认删除 会返回confirm字符串
        // 如果用户取消删除 会返回cancel字符串
        if (confirmResult !== 'confirm') {
            return this.$message.info('您取消了删除操作');
        }
        const {data: res} = await this.$http.delete('roles/' + id);
        if (res.meta.status !== 200) {
            return this.$message.error('删除角色信息失败!');
        }
        this.$message.success('删除角色信息成功!');
        // 刷新角色列表
        this.getRolesList();
    }

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/cJgQ!GeXwTuC.png
监听添加角色对话框的关闭事件 重置表单

    // 监听添加角色对话框的关闭事件
    addRolesDialogClosed() {
      // 重置添加角色对话框表单
      this.$refs.addRolesFormRef.resetFields();
    }

监听修改角色对话框的关闭事件 重置表单

    editRolesDialogClosed() {
      // 重置修改角色对话框表单
      this.$refs.editRolesFormRef.resetFields();
    }

添加用户的验证规则

 // 添加角色数据表单的验证规则
          addRolesFormRules: {
              roleName: [
                  { required: true, message: '请输入角色名称', trigger: 'blur' }
              ],
              roleDesc: [
                  { required: true, message: '请输入角色描述', trigger: 'blur' }
              ]
          }
  1. 分配角色权限(按需导入树形控件)

分配角色权限的对话框和树形控件

<!--      分配权限的对话框-->
      <el-dialog
        @close="setRightDialogClosed"
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%">
<!--        树形控件-->
        <el-tree ref="treeRef" default-expand-all :default-checked-keys="defKeys" node-key="id" show-checkbox :data="rightsList" :props="treeProps"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>

其中树形控件绑定的数据rightsList在data中定义

在打开对话框的时候调用事件处理函数为其赋值

   // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 为将要分配权限的角色id赋值
      this.roleId = role.id;
      // 获取树形权限列表
      const {data: res} = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) {
          return this.$message.error('获取权限树失败!');
      }
      this.rightsList = res.data;
      this.getLeafKeys(role, this.defKeys);
      // 打开对话框
      this.setRightDialogVisible = true;
    }

打开对话框的时候要获取那些权限是已有的

判断当前节点是否有children属性 如果没有 说明是三级权限 追加至三级权限数组中

// 通过递归的形式获取角色下所有三级权限的id 并保存到defKeys中
    getLeafKeys(node, arr) {
        // 如果当前node节点中没有children属性 则说明是第三级的权限 保存到数组中去 最后为defKeys赋值
        if (!node.children) {
            return arr.push(node.id);
        }
        // 如果有children属性则递归调用本函数 将三级权限的id保存到数组中
        node.children.forEach(item => {
            this.getLeafKeys(item, arr)
        });
    }

在点击对话框的确定按钮时发起分配角色权限的请求

 // 分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // 将数组转为以,分割
      const idStr = keys.join(',');
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {
          rids: idStr
      });
      if (res.meta.status !== 200) {
          return this.$message.error('分配权限失败!');
      }
      this.$message.success('分配权限成功!');
      this.getRolesList();
        // 关闭对话框
      this.setRightDialogVisible = false;
    }

https://gitee.com/xuoctober/image/raw/master/Vue学习笔记图片/RUEti^AC*I5c.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值