1、分配角色
1.1 前端代码分析
- 页面分析:src/views/system/sysUser/list.vue
<el-button type="warning" icon="el-icon-baseball" size="mini" @click="showAssignRole(scope.row)" title="分配角色"/>
showAssignRole (row) {this.sysUser = row//弹出分配角色窗口this.dialogRoleVisible = truethis.getRoles()},//sysUser: defaultForm,// const defaultForm = {// id: '',// username: '',// password: '',// name: '',// phone: '',// status: 1// }
getRoles () {
//将该用户的id传递给后台roleApi.getRoles(this.sysUser.id).then(response => {const {allRolesList, assginRoleList} = response.datathis.allRoles = allRolesListthis.userRoleIds = assginRoleList.map(item => item.id)this.checkAll = allRolesList.length===assginRoleList.lengththis.isIndeterminate = assginRoleList.length>0 && assginRoleList.length<allRolesList.length})},
- 添加 api,位置在:src/api/system/sysRole.js
getRoles(adminId) {return request({url: `${api_name}/toAssign/${adminId}`,method: 'get'})
},
1.2 后端代码分析
- controller层,操作类:SysRoleController
@ApiOperation(value = "根据用户获取角色数据")@GetMapping("/toAssign/{userId}")public Result toAssign(@PathVariable Long userId) {Map<String, Object> roleMap = sysRoleService.findRoleByAdminId(userId);return Result.ok(roleMap);}
- service层,操作类:SysRoleServiceImpl
@Autowiredprivate SysUserRoleMapper sysUserRoleMapper;@Overridepublic Map<String, Object> findRoleByAdminId(Long userId) {System.out.println(1);//1. 查询所有的角色List<SysRole> allRolesList = this.list();//2. 通过用户id查询中间表该所属全部角色id//第一种方法.推荐第二种方法//先查询中间表中属于该用户的信息List<SysUserRole> existUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId).select(SysUserRole::getRoleId));//2、遍历该用户的信息获取它全部的角色idList<Long> existRoleIdList = existUserRoleList.stream().map(c->c.getRoleId()).collect(Collectors.toList());//对角色进行分类,通过比较全部角色,获取属于该用户的角色信息List<SysRole> assginRoleList = new ArrayList<>();for (SysRole role : allRolesList) {//已分配if(existRoleIdList.contains(role.getId())) {assginRoleList.add(role);}}Map<String, Object> roleMap = new HashMap<>();//该用户的所属的角色信息roleMap.put("assginRoleList", assginRoleList);//全部角色信息roleMap.put("allRolesList", allRolesList);return roleMap;}
- 获取中间表该用户所属的全部角色id,第二种方法
@Repository
@Mapper
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
@Select("select role_id from sys_user_role where user_id=#{userId}")List<Long> AllRoleIds(@Param("userId") Long userId);}
1.3 后端执行完毕回调分析
- 页面位置:1. src/views/system/sysUser/list.vue
getRoles () {
//将该用户的id传递给后台roleApi.getRoles(this.sysUser.id).then(response => {//后台已经还行完毕const {allRolesList, assginRoleList} = response.data// allRoles: [], // 所有角色列表this.allRoles = allRolesList// userRoleIds: [], // 用户的角色ID的列表this.userRoleIds = assginRoleList.map(item => item.id)// checkAll: false // 是否全选//如果用户的角色是所有的角色那就是全选,如果不是则不是全选this.checkAll = allRolesList.length===assginRoleList.length//isIndeterminate: false, // 是否是不确定的this.isIndeterminate = assginRoleList.length>0 && assginRoleList.length<allRolesList.length})},
< <el-dialog title="分配角色" :visible.sync="dialogRoleVisible"><el-form label-width="80px"><el-form-item label="用户名"><el-input disabled :value="sysUser.username"></el-input></el-form-item><el-form-item label="角色列表"><el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox><div style="margin: 15px 0;"></div><el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange"><el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox></el-checkbox-group></el-form-item></el-form><div slot="footer"><el-button type="primary" @click="assignRole" size="small">保存</el-button><el-button @click="dialogRoleVisible = false" size="small">取消</el-button></div></el-dialog>
/*全选勾选状态发生改变的监听*/handleCheckAllChange (value) {// value 当前勾选状态true/false// 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组this.userRoleIds = value ? this.allRoles.map(item => item.id) : []// 如果当前不是全选也不全不选时, 指定为falsethis.isIndeterminate = false},/*角色列表选中项发生改变的监听*/handleCheckedChange (value) {//如果角色列表发生改变,则把数据进行更新const {userRoleIds, allRoles} = thisthis.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length},switchStatus(row) {row.status = row.status === 1 ? 0 : 1api.updateStatus(row.id, row.status).then(response => {if (response.code) {this.$message.success(response.message || '操作成功')this.dialogVisible = falsethis.fetchData()}})}}
2. 分配角色 保存操作
2.1 前端代码
- 页面,位置在:src/views/system/sysUser/list.vue
//当点击保存操作,则将该用户的id,和所属的角色信息给后台进行操作assignRole () {let assginRoleVo = {userId: this.sysUser.id,roleIdList: this.userRoleIds}roleApi.assignRoles(assginRoleVo).then(response => {this.$message.success(response.message || '分配角色成功')this.dialogRoleVisible = falsethis.fetchData(this.page)})},
- api,位置在:src/api/system/sysRole.js
assignRoles(assginRoleVo) {return request({url: `${api_name}/doAssign`,method: 'post',data: assginRoleVo})}
2.2 后端代码分析
- controller方法,SysRoleController
@ApiOperation(value = "根据用户分配角色")@PostMapping("/doAssign")public Result doAssign(@RequestBody AssginRoleVo assginRoleVo) {sysRoleService.doAssign(assginRoleVo);return Result.ok();}
2.service接口实现 操作类:SysRoleServiceImpl
@Transactional@Overridepublic void doAssign(AssginRoleVo assginRoleVo) {//删除数据库该用户的所属角色信息sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, assginRoleVo.getUserId()));
//遍历该用户的所属角色的idfor(Long roleId : assginRoleVo.getRoleIdList()) {if(StringUtils.isEmpty(roleId)) continue;//根据用户id,和角色id重新添加SysUserRole userRole = new SysUserRole();userRole.setUserId(assginRoleVo.getUserId());userRole.setRoleId(roleId);sysUserRoleMapper.insert(userRole);}}
3. 更改用户转态
用户状态:状态(1:正常 0:停用),当用户状态为正常时,可以访问后台系统,当用户状态停用后,不可以登录后台系统
3.1. 前端分析
- 页面分析,位置:src/views/system/sysUser/list.vue
<el-table-column label="状态" width="80"><template slot-scope="scope"><el-switchv-model="scope.row.status === 1"@change="switchStatus(scope.row)">
switchStatus(row) {
//获取转态是0 还是1 row.status = row.status === 1 ? 0 : 1api.updateStatus(row.id, row.status).then(response => {if (response.code) {this.$message.success(response.message || '操作成功')this.dialogVisible = falsethis.fetchData()}})}
- 添加api,位置:src/api/system/sysUser.js
updateStatus(id, status) {return request({url: `${api_name}/updateStatus/${id}/${status}`,method: 'get'})
}
3.2 后端代码分析
- controller方法,操作类:sysUserController
@ApiOperation(value = "更新状态")
@GetMapping("updateStatus/{id}/{status}")
public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {sysUserService.updateStatus(id, status);return Result.ok();
}
- service接口,操作类:sysUserService接口
void updateStatus(Long id, Integer status);
- service接口实现,操作类:sysUserServiceImpl
@Transactional
@Override
public void updateStatus(Long id, Integer status) {
//根据id进行查询SysUser sysUser = this.getById(id);if(status.intValue() == 1) {sysUser.setStatus(status);} else {sysUser.setStatus(0);}//修改数据this.updateById(sysUser);
}