08-尚硅谷-云尚办公【角色的删除、添加、修改、批量删除】

文章详细描述了如何在SpringBoot项目中,通过axios封装API,实现角色的增删改操作,包括角色列表查询、角色删除、添加角色、修改角色以及批量删除功能,并展示了前端组件中如何调用这些API完成用户交互。
摘要由CSDN通过智能技术生成

一、角色删除

1. 修改api

import request from '@/utils/request'//封装了axios相关内容

const api_name = '/admin/system/sysRole'
export default{
    // 角色列表-条件分页查询
    // 与后端匹配
    getPageList(current,limit,searchObj) {
        return request({
            url: `${api_name}/${current}/${limit}`,
            method: 'get',
            //如果普通对象参数写法 params:对象参数名称
            //如果使用json格式传递,data:对象参数名称
            params:searchObj
        })
    },
    // 角色删除
    removeById(id){
        return request({
            url:`${api_name}/remove/${id}`,
            method: 'delete',
        })
    }
}

2.组件中调用api:修改list.vue-编写删除方法

// 删除方法
  removeDataById(id) {
    // debugger element-vue自带组件
    this.$confirm("此操作将永久删除记录,是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 调用
        return api.removeById(id)
      })
      .then((response) => {
        // 刷新页面
        this.fetchData(this.page)
        // 提示信息
        this.$message.success(response.$message || "删除成功")
      });
  },
  //
  removeById(id){
    return requestAnimationFrame({
      url:'${api_name}/remove/${id}',
      methods:'delete'
    })
  },

3. 功能演示-测试删除功能

数据库情况

初始情况

删除第一条数据后的结果

二、角色添加

前端界面

1. 修改list.vue

增加添加按钮

        <!-- 工具条,添加按钮 -->
        <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>

添加增加功能的对话框

    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%" >
      <el-form ref="dataForm" :model="sysRole" label-width="150px" size="small" style="padding-right: 40px;">
        <el-form-item label="角色名称">
          <el-input v-model="sysRole.roleName"/>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="sysRole.roleCode"/>
        </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>

修改弹框的初始显示状态

修改add函数

 

修改前端添加增加功能中提到的的saveOrUpdate函数

 完成save函数

2.组件中调用api:修改list.vue-在sysRole.js中完成save方法中需要使用的saveRole函数

3. 功能演示-测试删除功能

增加前:

增加过程:

增加后:

三、修改

1. 修改api

2.组件中调用api:修改list.vue

3. 功能演示-测试修改功能

修改“角色管理员2”的角色编码为“manager2”

修改前:

修改:

修改后:

四、批量删除

1. 修改api

2.组件中调用api:修改list.vue

2.1 增加批量删除按钮

2.2 批量选择

复选框已经添加过

完成复选框函数-handeleSelectionChange

复选框功能测试

2.3 批量删除功能函数

3. 功能演示-测试修改功能

五、完整代码

1. 前端

api:sysRole.js

import request from '@/utils/request'//封装了axios相关内容

const api_name = '/admin/system/sysRole'
export default{
    // 角色列表-条件分页查询
    // 与后端匹配
    getPageList(current,limit,searchObj) {
        return request({
            url: `${api_name}/${current}/${limit}`,
            method: 'get',
            //如果普通对象参数写法 params:对象参数名称
            //如果使用json格式传递,data:对象参数名称
            params:searchObj
        })
    },
    // 角色删除
    removeById(id){
        return request({
            url:`${api_name}/remove/${id}`,
            method: 'delete',
        })
    },
    // 角色添加
    saveRole(role){
        //console.log("saverole",role)
        return request({
            url:`${api_name}/save`,
            method:'post',
            //data:{}
            params:role
        })
    },
    // 根据id查询
    getById(id){
        return request({
            url:`${api_name}/get/${id}`,
            method:'get'
        })
    },
    // 修改
    updateById(role){
        //console.log("updaterole",role)
        return request({
            url:`${api_name}/update`,
            method:'put',
            data:role
        })
    },
    // 批量删除
    batchRemove(idList){
        return request({
            url:`${api_name}/batchRemove`,
            method:'delete',
            data:idList
        })
    }
}

页面:list.vue

<!--><template>
  <div class="app-container">
    角色列表
  </div>
</template>
-->
<template>
  <div class="app-container">
  角色列表
    <!--查询表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称">
              <el-input style="width: 100%" v-model="searchObj.roleName" placeholder="角色名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex;">
          <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="fetchData()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" :loading="loading" @click="restData">重置</el-button>
          <!-- 工具条,添加按钮 -->
          <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
          <!-- 工具条,批量删除按钮 -->
          <el-button class="btn-add" size="mini" @click="batchRemove()">批量删除</el-button>
        </el-row>
      </el-form>
    </div>
    <!--表格-->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px;"
      @selection-change="handeleSelectionChange">
      <el-table-column type="selection"/>

      <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="roleName" label="角色名称"/>
      <el-table-column prop="roleCode" label="角色编码"/>
      <el-table-column prop="createTime" label="创建时间" width="160"/>
      <el-table-column label="操作" width="200" align="center">
        <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="3"
      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="sysRole" label-width="150px" size="small" style="padding-right: 40px;">
        <el-form-item label="角色名称">
          <el-input v-model="sysRole.roleName"/>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="sysRole.roleCode"/>
        </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>
//1. 引入定义接口的js文件
import api from '@/api/system/sysRole'
import Axios from 'axios';

export default{
    // 2.vue代码结构
    // 定义初始值
    data(){
      return{
        list:[],//角色列表
        page:1,//当前页
        limit:3,//每页显示记录数
        total:0,//总记录数
        searchObj:{},//条件对象

        sysRole:{},//用于封装添加功能的表单中的数据
        dialogVisible:false,// 添加功能的弹出框
        selections:[]//多个复选框中的值

      }
    },
    // 
    created() { //渲染之前执行
      this.fetchData()
    },
    //操作方法
     methods: {
      // 条件分页查询
      fetchData(current = 1) {
        this.page = current;
        api.getPageList(this.page, this.limit, this.searchObj)
        .then((response) => {
          this.list = response.data.records;
          // 查询结果是全部,后面需要核实
          //console.log("this.list",this.list)
          this.total = response.data.records.length;
        });
      },
      // 删除方法
      removeDataById(id) {
        // debugger element-vue自带组件
        this.$confirm("此操作将永久删除记录,是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 调用
          return api.removeById(id)
        }).then((response) => {
          // 刷新页面
          this.fetchData(this.page)
          // 提示信息
          this.$message.success(response.$message || "删除成功")
        });
      },
      //点击添加弹出框
      add() {
        this.dialogVisible = true
      },
      // 添加或修改
      saveOrUpdate(){
        this.saveBtnDisable = true // 防止表单重复提交
        // 根据id进行判断
        if(!this.sysRole.id){
          this.save()
        } else {
          this.update()
        }
      },
      // 增加方法
      save() {
        api.saveRole(this.sysRole)
        .then((response) => {
          // 刷新页面
          this.fetchData()
          //关闭弹框
          this.dialogVisible = false
          // 提示信息
          this.$message.success(response.$message || "添加成功")
        });
      },
      // 点击修改弹出框,根据id查询进行数据的显示
      edit(id){
        // 弹出框
        this.dialogVisible = true
        // 根据id进行查询
        this.fetchDataById(id)
      },
      // 完成fetchDataById函数
      fetchDataById(id){
        // 调用api中的getById方法
        api.getById(id).then(response => {
          //弹出框中利用v-model进行数据绑定,完成数据回显
          this.sysRole = response.data
        })
      },
      //修改      
      update() { 
        console.log("update")
        api.updateById(this.sysRole)
        .then(response => {
          //关闭弹框
          this.dialogVisible = false
          //刷新页面
          this.fetchData()
          //提示
          this.$message.success(response.message || '修改成功')
        })
      },
      // 复选框功能函数
      // 选择复选框后会把该行的内容进行传递
      handeleSelectionChange(selection){
        this.selections = selection
        console.log(this.selections)
      },
      // 批量删除
      batchRemove(){
        // 判断
        if(this.selections.length == 0){
          this.$message.warning('请选择要删除的记录!')
          return
        }
        this.$confirm('此操作将删除所选记录,是否继续?','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'}).then(()=>{          
            // 点击确定
            var idList = []
            // 遍历数组
            this.selections.forEach(element => {
              var id = element.id
              idList.push(id)
            });
            // 调用api
            return api.batchRemove(idList)}).then(response => {
              // 提示信息
              this.$message.success(response.$message || "删除成功")
              // 刷新页面
              this.fetchData()
            })
      }
    }
};
</script>

2. 后端

SysRoleController.java

package com.yun.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.model.model.system.SysRole;
import com.yun.model.vo.system.SysRoleQueryVo;
import com.yun.oa.service.SysRoleService;
import com.yun.utils.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
 * @paragram: myyunshangbangong
 * @description:
 * @author:
 * @create: 2024-01-11
 */
@Api(tags = "角色管理接口")
@RestController
@RequestMapping("/admin/system/sysRole")
public class SysRoleController {
    // 注入service
    @Autowired
    private SysRoleService sysRoleService;

//    // 查询所有角色
//    @GetMapping("/findAll")
//    public List<SysRole> findAll(){
//        List<SysRole> sysRoles = sysRoleService.list();
//        return sysRoles;
//    }

    /**
     * 统一返回数据结果
     * 查询所有角色
     * @return
     */
    @ApiOperation("查询所有角色")
    @GetMapping("/findAll")
    public Result findAll(){
        List<SysRole> sysRoles = sysRoleService.list();
        return Result.ok(sysRoles);
    }

    /**
     * 条件分页查询
     * page 当前页 limit 每页显示记录数
     * SysRoleQueryVo 条件对象
     * @return
     */
    @ApiOperation("条件分页查询")
    @GetMapping("{page}/{limit}")
    public Result pageQueryRole(@PathVariable Long page,
                                @PathVariable Long limit,
                                SysRoleQueryVo sysRoleQueryVo){
        //调用service的方法实现
        //1 创建Page对象,传递分页相关参数
        //page 当前页  limit 每页显示记录数
        Page<SysRole> pageParam = new Page<>(page,limit);

        //2 封装条件,判断条件是否为空,不为空进行封装
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        String roleName = sysRoleQueryVo.getRoleName();
        if(!StringUtils.isEmpty(roleName)) {
            //封装 like模糊查询
            wrapper.like(SysRole::getRoleName,roleName);
        }

        //3 调用方法实现
        IPage<SysRole> pageModel = sysRoleService.page(pageParam, wrapper);
        return Result.ok(pageModel);
    }

    // 添加角色
    @ApiOperation("添加角色")
    @PostMapping("save")
    public Result save(SysRole sysRole){
    //public Result save(@RequestBody SysRole sysRole){// 前端data: 报错,修改后能够保存
        // 调用service中的方法实现
        boolean is_success = sysRoleService.save(sysRole);
        if(is_success){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    // 修改角色-根据id查询
    @ApiOperation("根据id进行查询")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id){
        // 模拟异常效果
        // 全局+特定 先扫描特定然后扫描全局
//        int i = 10/0;
//        // 自定义异常处理
//        try {
//            int j = 10/0;
//        }catch (Exception e){
//            // 抛出自定义异常
//            throw new MyException(20001,"执行了自定义异常");
//        }
        SysRole sysRole = sysRoleService.getById(id);
        return Result.ok(sysRole);
    }

    // 修改角色-最终修改
    @ApiOperation("修改角色-最终修改")
    @PutMapping("update")
    public Result update(@RequestBody SysRole sysRole){
        // 调用service中的方法实现
        boolean is_success = sysRoleService.updateById(sysRole);
        if(is_success){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    // 根据id删除
    @ApiOperation("根据id删除")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id){
        System.out.println("remove**************");
        boolean is_success = sysRoleService.removeById(id);
        if(is_success){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    // 批量删除
    // 前端数组[1,2,3]
    @ApiOperation("批量删除")
    @DeleteMapping("batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList){
        boolean is_success = sysRoleService.removeByIds(idList);
        if(is_success){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值