// 创建rights子分支
git checkout -b rights
// 将本地的rights分支推送到码云
git push -u origin rights
1. 权限列表
1.1 通过路由展示权限列表组件
- 新建components/power/Rights.vue
- 引入路由
//router.js
import Rights from './components/power/Rights.vue'
const routes = [
{
path: '/home',
component: Home,
children: [
{ path: '/rights', component: Rights }
]
},
]
1.2 面包屑导航+卡片视图
<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>
123
</el-card>
</div>
</template>
1.3 调用API获取权限列表的数据
<script>
export default {
data() {
return {
//所有的权限列表数据
rightsList:[],
}
},
created(){
//生命周期函数created发起数据请求
//获取所有的权限,调用getRightsList这个函数
this.getRightsList()
},
methods:{
//1.4.1所有权限列表API接口中请求方式是get,type选择list(列表性质结构)
//获取权限列表方法
async getRightsList(){
const {data:res} = await this.$http.get('rights/list')
if(res.meta.status !== 200){
return this.$message.error('获取权限列表失败!')
}
//请求成功,将请求到的数据挂载到rightsList中,供页面的模板结构使用
this.rightsList = res.data
console.log(this.rightsList)
}
},
}
</script>
rightsList 返回一个数组,长度是48
1.4 渲染权限列表UI结构
//elememt.js
import { Tag } from 'element-ui'
Vue.use(Tag)
//Rights.vue
<!-- 卡片视图 -->
<el-card>
<!-- :data绑定数据源 border添加表格横竖边框线 stripe实现表格隔行变色
el-table-column是索引列 label是列的标题 prop是对应的具体属性值(根据响应数据) -->
<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">
<!-- 作用域插槽的形式来自定义输出格式 scope接收所有数据 -->
<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>
2. 权限管理业务分析
通过权限管理模块控制不同的用户可以进行哪些操作,具体可以通过角色的方式进行控制,即每个用户分配一个特定的角色,角色包括不同的功能权限
3. 角色列表
3.1 通过路由展示角色列表组件
- 新建components/power/Roles.vue
- 引入路由
import Roles from './components/power/Roles.vue'
const routes = [
{
path: '/home',
component: Home,
children: [
{path: '/roles', component: Roles }
]
},
]
3.2 绘制基本布局结构并获取列表数据
<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-row>
<el-col>
<el-button type="primary">添加角色</el-button>
</el-col>
</el-row>
//角色列表区域
<el-table border stripe>
</el-table>
</el-card>
</div>
</template>
<script>
export default {
data(){
return{
//所有角色列表数据
rolelist:[]
}
},
created(){
this.getRolesList()
},
methods:{
//获取所有角色的列表
async getRolesList(){
const {data:res} = await this.$http.get('roles')
if(res.meta.status !== 200){
return this.$message.error('获取角色列表失败')
}
this.rolelist=res.data
//打印结果如上图,返回一个Array(6)
console.log(this.rolelist)
}
},
}
</script>
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="操作">
<template slot-scope="scope">
<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项目实战:电商后台管理系统(三)------ 用户管理模块 (用户列表 /添加修改删除用户)
//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-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"></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="操作">
<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="removeRolesById(scope.row.id)">删除</el-button>
<el-button size="mini" type="warning" icon="el-icon-setting">分配角色</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 1. 添加角色的对话框 -->
<!-- visible控制对话框的显示隐藏 -->
<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>
<!-- 2. 编辑角色对话框 -->
<el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
<!-- 内容主体区域 -->
<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
<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="editRoleInfo">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
//所有角色列表数据
rolelist: [],
//控制添加角色对话框的显示与隐藏
addDialogVisible: false,
// 1.添加角色的表单数据
addForm: {
roleName: '',
roleDesc: '',
},
// 1.添加角色的验证规则对象
addFormRules: {
roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
},
// 2. 控制编辑角色对话框的显示与隐藏
editDialogVisible: false,
//查询到的角色对象
editForm: {},
editFormRules: {
roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
},
}
},
created() {
this.getRolesList()
},
methods: {
//获取所有角色的列表
async getRolesList() {
const { data: res } = await this.$http.get('roles')
if (res.meta.status !== 200) {
return this.$message.error('获取角色列表失败')
}
this.rolelist = res.data
console.log(this.rolelist)
},
// 1.监听添加用户对话框的关闭事件
addDialogClosed() {
this.$refs.addFormRef.resetFields()
},
//1.点击确定按钮,添加新用户
addRole() {
this.$refs.addFormRef.validate(async (valid) => {
//valid会返回一个布尔值,如果true就表示校验通过,反之false
//validate是element-ui表单的一个验证方法
if (!valid) return //失败了,直接return
//验证成功,发起添加用户的网络请求
const { data: res } = await this.$http.post('roles', this.addForm)
if (res.meta.status != 201) {
this.$message.error('添加角色失败')
}
this.$message.success('添加角色成功')
//隐藏添加用户的对话框
this.addDialogVisible = false
//重新获取用户列表数据
this.getRolesList()
})
},
// 展示编辑角色的对话框
async showEditDialog(id) {
this.editDialogVisible = true
const { data: res } = await this.$http.get('roles/' + id)
if (res.meta.status !== 200) {
return this.$message('查询角色信息失败!')
}
//查询到的数据保存到editForm 上
this.editForm = res.data
},
editDialogClosed() {
this.$refs.editFormRef.resetFields()
},
editRoleInfo() {
this.$refs.editFormRef.validate(async (valid) => {
if (!valid) return
const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
roleName: this.editForm.roleName,
roleDesc: this.editForm.roleDesc,
})
if (res.meta.status !== 200) {
return this.$message.error('更新角色信息失败!')
}
this.editDialogVisible = false
this.getRolesList()
this.$message.success('更新角色信息成功!')
})
},
async removeRolesById(id) {
const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).catch((error) => error)
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()
},
},
}
</script>
<style lang="less" scoped>
</style>
3.5 通过第一层for循环渲染一级权限
美化一级权限的UI结构:添加边框线,添加图标
// 展开列
<el-table-column type="expand">
<template slot-scope="scope">
<!-- el-row el-col 实现栅格布局 -->
<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>
</template>
</el-table-column>
.el-tag {
margin: 7px;
}
.bdtop {
border-top: 1px solid #eee;
}
.bdbottom {
border-bottom: 1px solid #eee;
}
3.6 通过第二层、第三层for循环渲染二级、三级权限、美化UI结构
// 渲染二级和三级权限
<el-col :span="19">
<!-- 通过for循环,嵌套渲染二级权限 -->
<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">{{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>
.vcenter {
display: flex;
align-items: center;
}
3.7 点击删除权限
给权限标签添加属性
<el-tag closable @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" v-for="item3 in item2.children" :key="item3.id" 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('已取消删除')
}
const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
if (res.meta.status !== 200) {
return this.$message.error('删除权限失败!')
}
this.$message.success('删除权限成功!')
//把服务器返回的最新权限直接赋值给当前角色的children属性, 可以防止整个列表刷新,提升用户体验
role.children = res.data
},
4. 分配权限
4.1 弹出分配权限限制对话框并请求数据
<el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog">分配权限</el-button>
data() {
return {
//3.控制分配权限对话框的显示与隐藏
setRightDialogVisible:false,
//所有权限的数据
rightslist:[]
}
}
//展示分配权限的对话框
async showSetRightDialog() {
this.setRightDialogVisible=true
//获取所有权限列表
const {data:res} = await this.$http.get('rights/tree')
if(res.data.status !==200 ){
return this.$message.error('获取权限数据失败!')
}
//获取到的权限数据,保存到data中
this.rightslist= res.data
},
4.2 初步配置并使用el-tree树形控件
//element.js
import { Tree } from 'element-ui'
Vue.use(Tree)
<!-- 树形控件 -->
<el-tree :data="rightslist" :props="treeProps"></el-tree>
data() {
return {
// 树形控件的属性绑定对象
treeProps: {
children: 'children',
label: 'authName'
}
}
}
4.3 优化树形控件的展示效果
- 添加复选框 show-checkbox
- 指定复选框选中的是id node-key=“id”
- 默认展开所有节点 default-expand-all
<el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all></el-tree>
4.4 已有权限默认选中
<el-button size="mini" type="warning" icon="el-icon-setting" @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: res } = await this.$http.get('rights/tree')
if (res.meta.status !== 200) {
return this.$message.error('获取权限数据失败!')
}
//获取到的权限数据,保存到data中
this.rightslist = res.data
//递归获取三级节点的id
this.getLeafKeys(role,this.defKeys)
this.setRightDialogVisible = true
},
//通过递归函数的形式,获取角色列表下所有三级权限的id,并保存到defKeys数组中
getLeafKeys(node,array){
//如果当前node节点不包含children属性,则是三级节点
if(!node.children){
return array.push(node.id)
}
//递归完毕后,把所有三级节点都遍历完,并且把id保存到array中
node.children.forEach(item =>
this.getLeafKeys(item,array))
},
4.5 在关闭对话框时重置defKeys数组
<!-- 分配权限的对话框 -->
<el-dialog title="分配权限" @close="setRightDialogClosed">
// 监听分配权限对话框的关闭事件
setRightDialogClosed() {
this.defKeys = []
}
//上面是一种方法,还可以用下面的方式
//递归之前先清空数组,赋值空
this.defKeys=[]
//递归获取三级节点的id
this.getLeafKeys(role,this.defKeys)
4.6 调用API完成分配权限的功能
1. 点开分配权限对话框时拿到角色id
<el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
data() {
return {
//当前即将分配权限的角色id
roleId:[],
}
},
//展示分配权限的对话框
async showSetRightDialog(role) {
this.roleId = role.id
}
2. 调用API分配权限
<!-- 内容主体区域 树形控件-->
<el-tree ref="treeRef"></el-tree>
<el-button type="primary" @click="allotRights">确 定</el-button>
//组件你可以认为是一个盒子,ref就是你给这个盒子打了一个特殊的标签,然你有了这个标签,你就可以去这个盒子里面拿她的东西
//点击确定为角色分配权限
async allotRights(){
const keys = [
//...就是把两个数组合并成一个数组 ...是展开 相当于把括号去掉
...this.$refs.treeRef.getCheckedKeys(), //获取所有已选中节点的id数组
...this.$refs.treeRef.getHalfCheckedNodes() //获取所有半选中节点的id数组
]
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
},
5. 完成用户管理-用户列表-分配角色功能 Users.vue
5.1 渲染分配角色的对话框并请求角色列表数据
<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
<!-- 分配角色的对话框 -->
<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>
data() {
return {
//控制分配角色的显示与隐藏
setRoleDialogVisible: false,
//需要被分配角色的用户信息
userInfo: {},
//所有角色的数据列表
rolesList: [],
}
},
//展示分配角色的对话框
async setRole(userInfo) {
this.userInfo = userInfo
//展示对话框之前,获取所有角色列表
const { data: res } = await this.$http.get('roles')
if (res.meta.status !== 200) {
return this.$message.error('获取角色列表失败!')
}
this.$message.success('获取角色列表成功!')
this.rolesList = res.data
this.setRoleDialogVisible = true
},
5.2 渲染角色列表的select下拉菜单
import { Select,Option } from 'element-ui'
Vue.use(Select)
Vue.use(Option)
<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-dialog @close="setRoleDialogClosed">
<el-button type="primary" @click="saveRoleInfo">确 定</el-button>
//点击按钮分配角色
async saveRoleInfo(){
if(!this.selectedRoleId){
return this.$message.error('请选择要分配的角色')
}
const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectedRoleId})
if(res.meta.status!==200){
return this.$message.error('更新角色失败!')
}
this.$message.success('更新角色成功!')
this.getUserList()
this.setRoleDialogVisible=false
},
//监听分配角色对话框的关闭事件
setRoleDialogClosed(){
this.selectedRoleId =''
this.userInfo = {}
},
6. 提交代码
git branch
git add .
git commit -m "完成了权限功能的开发"
git push --set-upstream origin rights
git checkout master
git merge rights
git push