🌻🌻 目录
- 一、用户管理
- 1.1、代码生成器
- 1.2、用户管理后端 CRUD
- 1.2.1、controller
- 1.2.2、service 接口
- 1.2.3、service 接口实现
- 1.2.4、mapper
- 1.2.5、xml
- 1.2.6、knife4j 测试
- 1.3、用户管理前端 CRUD
- 1.3.1、添加路由
- 1.3.2、定义基础 api
- 1.3.3、实现页面功能
- 1.3.4、 功能测试
- 1.3.5、添加用户
- 1.3.6、修改用户删除用户
- 1.3.7、 更改用户状态
- 1.3.7.1、 需求分析
- 1.3.7.2、设置数据库默认为 1
- 1.3.7.3、 controller方法
- 1.3.7.4、service接口
- 1.3.7.5、service接口实现
- 1.3.7.6、前端实现
- 二、给用户分配角色
- 2.1、给用户分配角色后端
- 2.1.1、接口分析
- 2.1.2、添加SysUserRoleMapper类
- 2.1.3、controller 方法
- 2.1.4、service接口
- 2.1.5、service接口实现
- 2.2、给用户分配角色前端
- 2.2.1、添加 api
- 2.2.2、修改页面
- 2.2.3、测试
一、用户管理
需要开发的功能:
条件分页查询用户
,用户添加
,用户修改
,用户删除
,为用户分配角色
(一个用户可以有多个角色,一个角色里可以有多个用户)
1.1、代码生成器
参考 👉👉MyBatis-Plus
https://baomidou.com/
打开自己的工程:
- ① 导入依赖:
<!--代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
- ② 在对应的
test
下面创建CodeGet.java
,然后导入下面,并做稍微修改即可。
package com.gansu.system;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class CodeGet {
public static void main(String[] args) {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("D:\\develop\\ideaIU-2018.2.5\\ideaIU-2018.2.5\\idea_workspace\\gansu-auth-parent\\service-system"+"/src/main/java");
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setAuthor("gansu");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/gansu-auth?serverTimezone=GMT%2B8&useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.gansu");
pc.setModuleName("system"); //模块名
pc.setController("controller");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("sys_user");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
③ 运行生成如下所示并做稍微修改:
修改后如下所示:
1.2、用户管理后端 CRUD
1.2.1、controller
SysUserController
package com.gansu.system.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gansu.common.result.Result;
import com.gansu.model.system.SysUser;
import com.gansu.model.vo.SysUserQueryVo;
import com.gansu.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 用户表 前端控制器
* </p>
*
* @author gansu
* @since 2024-08-24
*/
@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/system/sysuser")
public class SysUserController {
@Autowired
private SysUserService sysUserService;
// 1.通过分页查询所有用户接口
@ApiOperation(value = "分页查询所有用户")
@GetMapping("{page}/{limit}")
public Result selectAllUserByPage(
@PathVariable Long page,
@PathVariable Long limit,
SysUserQueryVo sysUserQueryVo){
Page<SysUser> pageParam = new Page(page,limit);
IPage<SysUser> pageModel = sysUserService.selectAllUserByPages(pageParam,sysUserQueryVo);
return Result.ok(pageModel);
}
// 2.新增用户接口
@ApiOperation(value = "新增用户")
@PostMapping("addUser")
public Result addUser(@RequestBody SysUser sysUser){
boolean isIsuccess = sysUserService.save(sysUser);
if(isIsuccess){
return Result.ok();
}else{
return Result.fail();
}
}
// 3.通过id查询用户接口
@ApiOperation(value = "通过id查询用户")
@GetMapping("selectUserById/{id}")
public Result selectUserById(@PathVariable String id){
SysUser byId = sysUserService.getById(id);
return Result.ok(byId);
}
// 4.通过id修改用户
@ApiOperation(value = "通过id修改用户")
@PutMapping("updateUserById")
public Result updateUserById(@RequestBody SysUser sysUser){
boolean isIsuccess = sysUserService.updateById(sysUser);
if(isIsuccess){
return Result.ok();
}else{
return Result.fail();
}
}
// 5.通过id删除用户
@ApiOperation(value = "通过id删除用户")
@DeleteMapping("deleteUserById/{id}")
public Result deleteUserById(@PathVariable String id){
boolean removeById = sysUserService.removeById(id);
return Result.ok();
}
}
1.2.2、service 接口
SysUserService 接口
package com.gansu.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gansu.model.system.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gansu.model.vo.SysUserQueryVo;
/**
* <p>
* 用户表 服务类
* </p>
*
* @author gansu
* @since 2024-08-24
*/
public interface SysUserService extends IService<SysUser> {
IPage<SysUser> selectAllUserByPages(Page<SysUser> pageParam, SysUserQueryVo sysUserQueryVo);
}
1.2.3、service 接口实现
SysUserServiceImpl 接口实现
package com.gansu.system.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gansu.model.system.SysUser;
import com.gansu.model.vo.SysUserQueryVo;
import com.gansu.system.mapper.SysUserMapper;
import com.gansu.system.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 用户表 服务实现类
* </p>
*
* @author gansu
* @since 2024-08-24
*/
@Transactional
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
@Override
public IPage<SysUser> selectAllUserByPages(Page<SysUser> pageParam, SysUserQueryVo sysUserQueryVo) {
IPage<SysUser> userIPage = baseMapper.selectAllUserByPages(pageParam,sysUserQueryVo);
return userIPage;
}
}
1.2.4、mapper
SysUserMapper
package com.gansu.system.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gansu.model.system.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gansu.model.vo.SysUserQueryVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* <p>
* 用户表 Mapper 接口
* </p>
*
* @author gansu
* @since 2024-08-24
*/
@Repository
public interface SysUserMapper extends BaseMapper<SysUser> {
//通过分页查询所有用户
IPage<SysUser> selectAllUserByPages(Page<SysUser> pageParam, @Param("vo") SysUserQueryVo sysUserQueryVo);
}
1.2.5、xml
搜索条件暂时只加现有的,其他条件后续补充
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gansu.system.mapper.SysUserMapper">
<resultMap id="UserMap" type="com.gansu.model.system.SysUser" autoMapping="true">
</resultMap>
<select id="selectAllUserByPages" resultMap="UserMap">
select id,username,password,name,phone,head_url,post_id,dept_id,
description,status,create_time,update_time,is_deleted from sys_user
<where>
<if test="vo.keyword != null and vo.keyword != ''">
AND (username like CONCAT('%',#{vo.keyword},'%')
or name like CONCAT('%',#{vo.keyword},'%')
or phone like CONCAT('%',#{vo.keyword},'%'))
</if>
<if test="vo.createTimeBegin != null and vo.createTimeBegin != ''">
and create_time >= #{vo.createTimeBegin}
</if>
<if test="vo.createTimeEnd != null and vo.createTimeEnd != ''">
and create_time <= #{vo.createTimeEnd}
</if>
and is_deleted = 0
</where>
ORDER BY id desc
</select>
</mapper>
1.2.6、knife4j 测试
http://localhost:8800/doc.html
1.3、用户管理前端 CRUD
1.3.1、添加路由
(上节应该添加了)
修改 src/router/index.js 文件
1.3.2、定义基础 api
创建文件 src/api/system/sysUser.js
crud可以一次性定义完
import request from '@/utils/request'
const api_name = '/admin/system/sysuser';
export default {
//用户列表
getPageUserList(page, limit, searchObj) {
return request({
url: `${api_name}/${page}/${limit}`, //这里的url一定要小写,不然识别不到
method: 'get',
params: searchObj
})
},
//用户添加
addUser(user) {
return request({
url: `${api_name}/addUser`,
method: 'post',
data: user
})
},
//根据用户id查询用户
findUserById(id) {
return request({
url: `${api_name}/selectUserById/${id}`,
method: 'get'
})
},
//修改用户
updateUserById(user) {
return request({
url: `${api_name}/updateUserById`,
method: 'put',
data: user
})
},
//删除用户
deleteUserById(id) {
return request({
url: `${api_name}/deleteUserById/${id}`,
method: 'delete'
})
}
}
1.3.3、实现页面功能
创建 src/views/system/sysUser/list.vue
① 导入如下修改过的 element-UI
模板
<template>
<div class="app-container">
<div class="search-div">
<el-form label-width="70px" size="small">
<el-row>
<el-col :span="8">
<el-form-item label="关 键 字">
<el-input style="width: 95%" v-model="searchObj.keyword" placeholder="用户名/姓名/手机号码"></el-input>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="操作时间">
<el-date-picker
v-model="createTimes"
type="datetimerange"
range-separator="至"
start-placeholder="开始时间"
end-placeholder="结束时间"
value-format="yyyy-MM-dd HH:mm:ss"
style="margin-right: 10px;width: 100%;"
/>
</el-form-item>
</el-col>
</el-row>
<el-row style="display:flex">
<el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData()">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
</el-row>
</el-form>
</div>
<!-- 工具条 -->
<div class="tools-div">
<el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
</div>
<!-- 列表 -->
<el-table
v-loading="listLoading"
:data="list"
stripe
border
style="width: 100%;margin-top: 10px;">
<el-table-column
label="序号"
width="70"
align="center">
<template slot-scope="scope">
{{ (page - 1) * limit + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column prop="username" label="用户名" width="180"/>
<el-table-column prop="name" label="姓名" width="110"/>
<el-table-column prop="phone" label="手机" />
<el-table-column label="状态" width="80">
<template slot-scope="scope">
<el-switch
:value ="scope.row.status === 1"
@change="switchStatus(scope.row)">
</el-switch>
</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间" />
<el-table-column label="操作" align="center" fixed="right">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)" title="修改"/>
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" />
</template>
</el-table-column>
</el-table>
<!-- 分页组件 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
style="padding: 30px 0; text-align: center;"
layout="total, prev, pager, next, jumper"
@current-change="fetchData"
/>
<el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%" >
<el-form ref="dataForm" :model="sysUser" label-width="100px" size="small" style="padding-right: 40px;">
<el-form-item label="用户名" prop="username">
<el-input v-model="sysUser.username"/>
</el-form-item>
<el-form-item v-if="!sysUser.id" label="密码" prop="password">
<el-input v-model="sysUser.password" type="password"/>
</el-form-item>
<el-form-item label="姓名" prop="name">
<el-input v-model="sysUser.name"/>
</el-form-item>
<el-form-item label="手机" prop="phone">
<el-input v-model="sysUser.phone"/>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
<el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
② 再先分页查出所有用户呗!!!
<script>
import api from '@/api/system/sysUser'
export default {
data(){
return{
listLoading: false, // 数据是否正在加载
list: null, // banner列表
total: 0, // 数据库中的总记录数
page: 1, // 默认页码
limit: 3, // 每页记录数
searchObj: {}, // 查询表单对象
createTimes: [],
dialogVisible: false,
sysUser: {}
}
},
created(){
this.fetchData()
},
methods:{
//重置
resetData(){
this.searchObj = {}
this.fetchData()
},
//用户列表显示
fetchData(page = 1){
if(this.createTimes && this.createTimes.length ==2) {
this.searchObj.createTimeBegin = this.createTimes[0]
this.searchObj.createTimeEnd = this.createTimes[1]
}
this.page = page;
api.getPageUserList(this.page,this.limit,this.searchObj)
.then(Response=>{
console.log(Response)
this.list = Response.data.records
this.total = Response.data.total
})
}
}
}
</script>
1.3.4、 功能测试
启动后端,前端进行测试:http://localhost:9528/#/system/sysUser
① 全局查询
② 搜索,重置都是可以的
1.3.5、添加用户
src/views/system/sysUser/list.vue
//添加或修改
saveOrUpdate(){
if(!this.sysUser.id){
this.addUser()
}else{
this.updateUserById()
}
},
//修改根据id
updateUserById(){
},
//弹框输入进行添加用户
addUser(){
api.addUser(this.sysUser).then(Response=>{
//提示
this.$message.success('操作成功'),
//关闭弹框
this.dialogVisible=false,
//刷新页面
this.fetchData()
})
},
//弹框显示添加功能
add(){
this.dialogVisible=true
this.sysUser ={}
},
测试:
数据库显示:
1.3.6、修改用户删除用户
src/views/system/sysUser/list.vue
① 修改
//修改根据id
updateUserById(){
api.updateUserById(this.sysUser).then(Response=>{
this.$message.success(Response.message || '操作成功')
this.dialogVisible = false,
this.fetchData()
})
},
//根据id查询用户(回显)
edit(id){
api.findUserById(id).then(Response =>{
//打开弹框
this.dialogVisible=true
this.sysUser = Response.data
})
},
② 删除操作
// 根据id删除数据
removeDataById(id){
this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 点击确定,远程调用ajax
api.deleteUserById(id).then(Response =>{
this.$message({
type: 'success',
message: '删除成功!'
});
//刷新页面或查询全部
this.fetchData()
})
})
},
1.3.7、 更改用户状态
1.3.7.1、 需求分析
用户状态:
状态(1:正常 0:停用)
,当用户状态为正常时,可以访问后台系统,当用户状态停用后,不可以登录后台系统
1.3.7.2、设置数据库默认为 1
1.3.7.3、 controller方法
操作类:
SysUserController
//更改用户状态
@ApiOperation("更改用户状态")
@GetMapping("updateUserStatus/{id}/{status}")
public Result updateUserStatus(
@PathVariable Long id,
@PathVariable Integer status){
sysUserService.updateUserStatus(id,status);
return Result.ok();
}
1.3.7.4、service接口
操作类:SysUserService
void updateUserStatus(Long id, Integer status);
1.3.7.5、service接口实现
操作类:SysUserServiceImpl
//更改用户状态
@Override
public void updateUserStatus(Long id, Integer status) {
SysUser sysUser = baseMapper.selectById(id);
sysUser.setStatus(status);
baseMapper.updateById(sysUser);
}
1.3.7.6、前端实现
① 添加api
src/api/system/sysUser.js
//修改用户状态
updateUserStatusById(id,status) {
return request({
url: `${api_name}/updateUserStatus/${id}/${status}`,
method: 'get'
})
}
② 修改页面
更改src/views/system/sysUser/list.vue
//修改用户状态
switchStatus(row){
row.status = row.status === 1 ? 0 : 1
api.updateUserStatusById(row.id,row.status).then(Response =>{
this.$message.success(Response.message || "修改成功")
this.fetchData()
})
},
③ 测试
修改前:
修改后:
二、给用户分配角色
2.1、给用户分配角色后端
2.1.1、接口分析
- 1、进入分配页面:获取已分配角色与全部角色,进行页面展示
- 2、保存分配角色:删除之前分配的角色和保存现在分配的角色
2.1.2、添加SysUserRoleMapper类
SysUserRoleMapper
package com.gansu.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gansu.model.system.SysUserRole;
import org.springframework.stereotype.Repository;
@Repository
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
}
2.1.3、controller 方法
两个接口,先完成一个,再写另外一个
//9.根据用户分配角色
@ApiOperation(value = "根据用户分配角色")
@PostMapping("doAssign")
public Result doAssign(@RequestBody AssginRoleVo assginRoleVo){
sysRoleService.doAssign(assginRoleVo);
return Result.ok();
}
//8.通过用户id获取角色id
@ApiOperation(value = "通过用户id获取角色")
@GetMapping("toAssign/{userId}")
public Result toAssign(@PathVariable Long userId){
Map<String,Object> roleMap = sysRoleService.getRoleByUserId(userId);
return Result.ok(roleMap);
}
2.1.4、service接口
操作类:SysRoleService
//通过用户id获取角色
Map<String, Object> getRoleByUserId(Long userId);
//根据用户分配角色
void doAssign(AssginRoleVo assginRoleVo);
2.1.5、service接口实现
操作类:SysRoleServiceImpl
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
//根据用户id获取角色
@Override
public Map<String, Object> getRoleByUserId(Long userId) {
//获取所有的角色
List<SysRole> roleList = baseMapper.selectList(null);
//条件查询:通过用户id查询所有的已分配角色
QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id",userId);
List<SysUserRole> userRoles = sysUserRoleMapper.selectList(queryWrapper);
//通过分配角色获取用户id
List<String> userRoleIds = new ArrayList<>();
for (SysUserRole userRole : userRoles) {
//将所有已经分配的存到一起
userRoleIds.add(userRole.getRoleId());
}
Map<String,Object> map = new HashMap<>();
map.put("allRoles",roleList); //所有的角色
map.put("userIds",userRoleIds);//用户已分配的角色的id集合
return map;
}
//根据用户分配角色
@Override
public void doAssign(AssginRoleVo assginRoleVo) {
//删除用户分配的角色
QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id",assginRoleVo.getUserId());
sysUserRoleMapper.delete(queryWrapper);
//获取所有的角色id
List<String> roleList = assginRoleVo.getRoleIdList();
for (String roleId:roleList) {
//进行重新分配 添加角色
SysUserRole userRole = new SysUserRole();
userRole.setUserId(assginRoleVo.getUserId());
userRole.setRoleId(roleId);
//保存
sysUserRoleMapper.insert(userRole);
}
}
2.2、给用户分配角色前端
2.2.1、添加 api
src/api/system/sysRole.js
//根据用户id查询用户已分配的角色
getRolesByUserId(userId) {
return request({
url: `${api_name}/toAssign/${userId}`,
method: 'get'
})
},
//分配角色
assignRoles(assginRoleVo) {
return request({
url: `${api_name}/doAssign`,
method: 'post',
data: assginRoleVo
})
}
2.2.2、修改页面
更改src/views/system/sysUser/list.vue
① 添加分配角色按钮
<el-button type="warning" icon="el-icon-baseball" size="mini" @click="showAssignRole(scope.row)" title="分配角色"/>
② 添加分配角色表单
<!-- 添加分配角色表单 -->
<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>
③ 添加方法
import api from '@/api/system/sysUser'
import roleApi from '@/api/system/sysRole'
export default {
data(){
return{
listLoading: false, // 数据是否正在加载
list: null, // banner列表
total: 0, // 数据库中的总记录数
page: 1, // 默认页码
limit: 3, // 每页记录数
searchObj: {}, // 查询表单对象
createTimes: [],
dialogVisible: false,
sysUser: {},
dialogRoleVisible: false,
allRoles: [], // 所有角色列表
userRoleIds: [], // 用户的角色ID的列表
isIndeterminate: false, // 是否是不确定的
checkAll: false // 是否全选
}
},
created(){
this.fetchData()
},
methods:{
//展示分配角色
showAssignRole (row) {
this.sysUser = row
this.dialogRoleVisible = true
roleApi.getRolesByUserId(row.id).then(response => {
this.allRoles = response.data.allRoles
console.log(this.allRoles)
this.userRoleIds = response.data.userRoleIds
console.log(this.allRoles)
this.checkAll = this.userRoleIds.length===this.allRoles.length
this.isIndeterminate = this.userRoleIds.length>0 && this.userRoleIds.length<this.allRoles.length
})
},
/*
全选勾选状态发生改变的监听
*/
handleCheckAllChange (value) {// value 当前勾选状态true/false
// 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
// 如果当前不是全选也不全不选时, 指定为false
this.isIndeterminate = false
},
/*
角色列表选中项发生改变的监听
*/
handleCheckedChange (value) {
const {userRoleIds, allRoles} = this
this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length
},
//分配角色
assignRole () {
let assginRoleVo = {
userId: this.sysUser.id,
roleIdList: this.userRoleIds
}
roleApi.assignRoles(assginRoleVo).then(response => {
this.$message.success(response.message || '分配角色成功')
this.dialogRoleVisible = false
this.fetchData(this.page)
})
},
}
}
</script>
2.2.3、测试
① 分配所有
② 重新分配
文章源码