【Vue】实战项目:电商后台管理系统(Element-UI)(三)权限管理模块

1. 权限管理业务分析

通过权限管理模块控制不同的用户可以进行哪些操作,具体可以通过角色的方式进行控制,即每个用户分配
一个特定的角色,角色包括不同的功能权限。
在这里插入图片描述

2. 权限列表

2.1 通过路由展示权限列表组件

  1. 新建components/power/Rights.vue
  2. 引入路由

2.2 面包屑导航+卡片视图

<!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>权限列表</el-breadcrumb-item>
</el-breadcrumb>

<!-- 卡片视图 -->
<el-card></el-card>

2.3 调用API获取权限列表的数据

export default {
    
    
  data() {
    
    
    return {
    
    
      // 权限列表
      rightsList: []
    }
  },
  created() {
    
    
    // 获取所有的权限
    this.getRightsList()
  },
  methods: {
    
    
    async getRightsList() {
    
    
      const {
    
     data: result } = await this.$http.get('rights/list')
      if (result.meta.status !== 200) {
    
    
        return this.$message.error('获取权限列表失败!')
      }
      this.rightsList = result.data
      console.log(this.rightsList)
    }
  }
}

2.4 渲染权限列表UI结构

<!-- 卡片视图 -->
<el-card>
  <el-table :data="rightsList" border stripe>
    <el-table-column type="index"></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">
      <template slot-scope="scope">
        <el-tag v-if="scope.row.level === '0'">一级</el-tag>
        <el-tag type="success" v-else-if="scope.row.level === '1'">二级</el-tag>
        <el-tag type="warning" v-else>三级</el-tag>
      </template>
    </el-table-column>
  </el-table>
</el-card>

3. 角色列表

3.1 通过路由展示角色列表组件

  1. 新建components/power/Roles.vue
  2. 引入路由

3.2 绘制基本布局结构并获取列表数据

<!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图 -->
<el-card>
  <!-- 添加角色按钮区域 -->
  <el-row>
    <el-col>
      <el-button type="primary">添加角色</el-button>
    </el-col>
  </el-row>
  <!-- 角色列表区域 -->
  <el-table border stripe>
  </el-table>
</el-card>
export default {
    
    
  data() {
    
    
    return {
    
    
      // 所有角色列表数据
      roleList: []
    }
  },
  created() {
    
    
    this.getRolesList()
  },
  methods: {
    
    
    // 获取所有角色的列表
    async getRolesList() {
    
    
      const {
    
     data:result } = await this.$http.get('roles')
      if(result.meta.status !== 200){
    
    
        return this.$message.error('获取角色列表失败!');
      }
      this.roleList = result.data
      console.log(this.roleList)
    }
  }
}

3.3 渲染角色列表数据

<!-- 角色列表区域 -->
<el-table :data="roleList" border stripe>
  <!-- 展开列 -->
  <el-table-column type="expand"></el-table-column>
  <!-- 索引列 -->
  <el-table-column 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="操作" width="300px">
    <template>
      <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
      <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
      <el-button size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
    </template>
  </el-table-column>
</el-table>

3.4 添加角色+编辑+删除操作

和用户管理中操作类似
【Vue】实战项目:电商后台管理系统(Element-UI)(二)用户管理模块

3.5 通过第一层for循环渲染一级权限

<!-- 展开列 -->
<el-table-column type="expand">
  <template slot-scope="scope">
    <el-row v-for="(item1, index1) in scope.row.children" :key="item1.id">
      <!-- 渲染一级权限 -->
      <el-col :span="5">
        <el-tag>{
   
   { item1.authName }}</el-tag>
      </el-col>
      <!-- 渲染二级、三级权限 -->
      <el-col :span="19"></el-col>
    </el-row>
    <!-- <pre>
      {
    
    {scope.row}}
    </pre> -->
  </template>
</el-table-column>

3.6 美化一级权限的UI结构

添加边框线
添加图标

<el-table-column type="expand">
  <template slot-scope="scope">
    <el-row 
    :class="['bdbottom', index1 === 0 ? 'bdtop' : '']" 
    v-for="(item1, index1) in scope.row.children" 
    :key="item1.id">
      <!-- 渲染一级权限 -->
      <el-col :span="5">
        <el-tag>{
   
   { item1.authName }}</el-tag>
        <i class="el-icon-caret-right"></i>
      </el-col>
      <!-- 渲染二级、三级权限 -->
      <el-col :span="19"></el-col>
    </el-row>
    <!-- <pre>
      {
    
    {scope.row}}
    </pre> -->
  </template>
</el-table-column>
.el-tag {
    
    
  margin: 7px;
}
.bdtop {
    
    
  border-top: 1px solid #eee;
}
.bdbottom {
    
    
  border-bottom: 1px solid #eee;
}

3.7 通过第二层、第三层for循环渲染二级、三级权限

<!-- 渲染二级、三级权限 -->
<el-col :span="19">
  <el-row
    :class="[index2 === 0 ? '' : 'bdtop']"
    v-for="(item2, index2) in item1.children"
    :key="item2.id"
  >
    <!-- 渲染二级权限 -->
    <el-col :span="6">
      <el-tag type="success">{
   
   { item2.authName }}</el-tag>
      <i class="el-icon-caret-right"></i>
    </el-col>
    <!-- 渲染三级权限 -->
    <el-col :span="18">
      <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id">{
   
   { item3.authName }}</el-tag>
    </el-col>
  </el-row>
</el-col>

3.8 美化UI结构

一级权限

<el-row
  :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
  v-for="(item1, index1) in scope.row.children"
  :key="item1.id"
>

二级权限

<el-row
  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
  v-for="(item2, index2) in item1.children"
  :key="item2.id"
>
.vcenter {
    
    
  display: flex;
  align-items: center;
}

3.9 点击删除权限

给权限标签添加属性

<el-tag close @close="removeRightById(scope.row, item1.id)">
{
   
   { item1.authName }}</el-tag>
<el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
{
   
   { item2.authName }}</el-tag>
<el-tag type="warning" closable @close="removeRightById(scope.row, item3.id)">
{
   
   { item3.authName }}</el-tag>
// 根据Id删除对应的权限
async removeRightById(role, rightId) {
    
    
  // 弹框提示用户是否删除数据
  const confirmResult = await this.$confirm(
    '此操作将永久删除该权限,是否继续?',
    '提示',
    {
    
    
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).catch(error => error)
  if (confirmResult !== 'confirm') {
    
    
    return this.$message.info('已经取消删除')
  }
  // console.log('确认了删除')
  const {
    
     data: result } = await this.$http.delete(
    'roles/' + role.id + '/rights/' + rightId
  )
  if (result.meta.status !== 200) {
    
    
    return this.$message.error('删除权限失败')
  }
  this.$message.success('删除权限成功')
  // this.getRolesList() // 会重新加载页面,不推荐使用
  role.children = result.data
}

在这里插入图片描述

4. 分配权限

4.1 弹出分配权限限制对话框并请求数据

<el-button @click="showSetRightDialog">分配权限</el-button>
<!-- 分配权限的对话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="50%"
>
  <!-- 内容主体区域 -->
  <!-- 底部区域 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRightDialogVisible = false">确 定</el-button>
  </span>
</el-dialog>

定义data数据

// 控制分配权限对话框显示与隐藏
setRightDialogVisible: false,
// 所有权限数据
rightslist: []
// 展示分配权限的对话框
async showSetRightDialog() {
    
    
  // 获取所有权限数据
  const {
    
     data: result } = await this.$http.get('rights/tree')
  if (result.meta.status !== 200) return this.$message.error('获取权限数据失败')
  // 获取到的权限数据保存到rightslist中
  this.rightslist = result.data
  console.log(this.rightslist)
  this.setRightDialogVisible = true
}

4.2 初步配置并使用el-tree树形控件

  <!-- 内容主体区域 树形控件-->
  <el-tree :data="rightslist" :props="treeProps"></el-tree>
data() {
    
    
  return {
    
    
    // 树形控件的属性绑定对象
    treeProps: {
    
    
      children: 'children',
      label: 'authName'
    }
  }
}

4.3 优化树形控件的展示效果

  1. 添加复选框 show-checkbox
  2. 指定复选框选中的是id node-key="id"
  3. 默认展开所有节点 default-expand-all
<el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all></el-tree>

在这里插入图片描述

4.4 已有权限默认选中

<el-button @click="showSetRightDialog(scope.row)">分配权限</el-button>
  <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
  // 默认选中的节点id值数组
  defKeys: []
// 展示分配权限的对话框
async showSetRightDialog(role) {
    
    
  // 获取所有权限数据
  const {
    
     data: result } = await this.$http.get('rights/tree')
  if (result.meta.status !== 200) return this.$message.error('获取权限数据失败')
  // 获取到的权限数据保存到rightslist中
  this.rightslist = result.data
  console.log(this.rightslist)
  // 递归获取三级节点的id
  this.getLeafKeys(role, this.defKeys)
  this.setRightDialogVisible = true
},
// 通过递归的形式,获取角色下所有三级权限的id,并保存到defKeys数组中
getLeafKeys(node, arr) {
    
    
  // 如果当前节点不包含children属性,则是三级权限节点
  if (!node.children) {
    
    
    return arr.push(node.id)
  }
  node.children.forEach(item => this.getLeafKeys(item, arr))
}

4.5 在关闭对话框时重置defKeys数组

 <!-- 分配权限的对话框 -->
<el-dialog title="分配权限" @close="setRightDialogClosed">
// 监听分配权限对话框的关闭事件
setRightDialogClosed() {
    
    
  this.defKeys = []
}

4.6 调用API完成分配权限的功能

  1. 点开对话框时拿到角色id
<el-button @click="showSetRightDialog(scope.row)">分配权限</el-button>
// 当前即将分配权限的角色id
roleId: ''
async showSetRightDialog(role) {
    
    
  this.roleId = role.id
}
  1. 调用API分配权限
<!-- 内容主体区域 树形控件-->
<el-tree ref="treeRef"></el-tree>
<el-button type="primary" @click="allotRights">确 定</el-button>
// 点击为角色分配权限
async allotRights() {
    
    
  const keys = [
    ...this.$refs.treeRef.getCheckedKeys(),
    ...this.$refs.treeRef.getHalfCheckedKeys()
  ]
  // console.log(keys)
  const idStr = keys.join(',')
  const {
    
    
    data: result
  } = await this.$http.post(`roles/${
      
      this.roleId}/rights`, {
    
     rids: idStr })
  if (result.meta.status !== 200) return this.$message.error('分配权限失败!')
  this.$message.success('分配权限成功')
  this.getRolesList()
  this.setRightDialogVisible = false
}

在这里插入图片描述

Roles.vue完整代码

<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, index1) 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="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{
   
   { item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{
   
   { item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {
    
    {scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column 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="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 内容主体区域 树形控件-->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></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>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      // 所有角色列表数据
      roleList: [],
      addDialogVisible: false,
      addForm: {
     
     
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
     
     
        roleName: [
          {
     
      required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的角色的信息对象
      editForm: {
     
     },
      // 控制分配权限对话框显示与隐藏
      setRightDialogVisible: false,
      // 所有权限数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
     
     
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
     
     
    this.getRolesList()
  },
  methods: {
     
     
    // 获取所有角色的列表
    async getRolesList() {
     
     
      const {
     
      data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) {
     
     
        return this.$message.error('获取角色列表失败!')
      }
      this.roleList = result.data
      console.log(this.roleList)
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
     
     
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色操作
    addRole() {
     
     
      this.$refs.addFormRef.validate(async valid => {
     
     
        if (!valid) return
        const {
     
      data: result } = await this.$http.post('roles', this.addForm)
        if (result.meta.status !== 201) {
     
     
          return this.$message.error('添加角色失败!')
        }
        this.$message.success('添加角色成功!')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
     
     
      this.editDialogVisible = true
      const {
     
      data: result } = await this.$http.get('roles/' + id)
      if (result.meta.status !== 200) {
     
     
        return this.$message('查询用户信息失败!')
      }
      this.editForm = result.data
    },
    editUserInfo() {
     
     
      this.$refs.editFormRef.validate(async valid => {
     
     
        // console.log(valid)
        if (!valid) return
        // 发起修改用户信息的数据请求
        const {
     
      data: result } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
     
      roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        )
        if (result.meta.status !== 200) {
     
     
          return this.$message.error('更新角色失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 重新获取用户列表
        this.getRolesList()
        // 提示修改成功
        this.$message.success('更新角色信息成功')
      })
    },
    // 根据id删除对应的用户信息
    async removeRoleById(id) {
     
     
      // 弹框提示用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色,是否继续?',
        '提示',
        {
     
     
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      // console.log(confirmResult) // 确定:'confirm' 取消:报错:cancel catch之后就是'canel'
      if (confirmResult !== 'confirm') {
     
     
        return this.$message.info('已经取消删除')
      }
      const {
     
      data: result } = await this.$http.delete('roles/' + id)
      if (result.meta.status !== 200) {
     
     
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
     
     
      // 弹框提示用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限,是否继续?',
        '提示',
        {
     
     
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmResult !== 'confirm') {
     
     
        return this.$message.info('已经取消删除')
      }
      // console.log('确认了删除')
      const {
     
      data: result } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + rightId
      )
      if (result.meta.status !== 200) {
     
     
        return this.$message.error('删除权限失败')
      }
      this.$message.success('删除权限成功')
      // this.getRolesList() // 会重新加载页面,不推荐使用
      role.children = result.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
     
     
      this.roleId = role.id
      // 获取所有权限数据
      const {
     
      data: result } = await this.$http.get('rights/tree')
      if (result.meta.status !== 200) return this.$message.error('获取权限数据失败')
      // 获取到的权限数据保存到rightslist中
      this.rightslist = result.data
      console.log(this.rightslist)
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式,获取角色下所有三级权限的id,并保存到defKeys数组中
    getLeafKeys(node, arr) {
     
     
      // 如果当前节点不包含children属性,则是三级权限节点
      if (!node.children) {
     
     
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
     
     
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
     
     
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const {
     
     
        data: result
      } = await this.$http.post(`roles/${
       
       this.roleId}/rights`, {
     
      rids: idStr })
      if (result.meta.status !== 200) return this.$message.error('分配权限失败!')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style scoped>
.el-tag {
     
     
  margin: 7px;
}
.bdtop {
     
     
  border-top: 1px solid #eee;
}
.bdbottom {
     
     
  border-bottom: 1px solid #eee;
}
.vcenter {
     
     
  display: flex;
  align-items: center;
}
</style>

5. 完成用户管理-用户列表-分配角色功能 Users.vue

5.1 渲染分配角色的对话框并请求角色列表数据

<!-- 分配角色的对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="50%"
>
  <!-- 内容主体区域 -->
  <div>
    <p>当前用户:{
   
   {userInfo.username}}</p>
    <p>当前角色:{
   
   {userInfo.role_name}}</p>
  </div>
  <!-- 底部区域 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoleDialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配角色按钮 添加消息提示 -->
<el-tooltip>
  <el-button @click="setRole(scope.row)"></el-button>
</el-tooltip>
// 控制分配角色对话框显示与隐藏
setRoleDialogVisible: false,
// 需要被分配角色的用户信息
userInfo: {
    
    }
// 所有角色的数据列表
rolesList: []
// 展示分配角色的对话框
setRole(userInfo) {
    
    
  this.userInfo = userInfo
  
  // 在展示对话框之前获取所有角色的列表
  const {
    
     data: result } = await this.$http.get('roles')
  if (result.meta.status !== 200) return this.$message.error('获取角色列表失败!')
  this.$message.success('获取角色列表成功!')
  this.rolesList = result.data

  this.setRoleDialogVisible = true
}

5.2 渲染角色列表的select下拉菜单

<p>分配新角色:
  <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
    </el-option>
  </el-select>
</p>
  // 已选中的角色id值
  selectedRoleId: ''

在这里插入图片描述

5.3 完成分配角色的功能

<el-button type="primary" @click="saveRoleInf">确 定</el-button>
// 点击按钮分配角色
async saveRoleInf() {
    
    
  if (!this.selectedRoleId) {
    
    
    return this.$message.error('请选择一个角色!')
  }
  const {
    
     data: result } = await this.$http.put(`users/${
      
      this.userInfo.id}/role`, {
    
     rid: this.selectedRoleId })
  if (result.meta.status !== 200) {
    
    
    return this.$message.error('更新角色失败!')
  }
  this.$message.success('更新角色成功!')
  // 刷新当前角色列表
  this.getUserList()
  // 隐藏当前分配角色对话框
  this.setRoleDialogVisible = false
}
<!-- 分配角色的对话框 -->
<el-dialog
  @close="setRoleDialogClosed"
>
// 监听分配角色对话框的关闭事件
setRoleDialogClosed() {
    
    
  this.selectedRoleId = ''
  this.userInfo = {
    
    }
}

6. 提交代码

git branch
git add .
git commit -m "完成了权限功能的开发"
git push
git checkout master
git merge rights
git push

猜你喜欢

转载自blog.csdn.net/weixin_44972008/article/details/114676742