SpringBoot+Vue之分页操作

2022年11月4日08:29:24

springboot–表格操作02

不建议使用mybatis自带的分页查询,或pagehelper插件等,使用MySql查询语句更方便快捷。

以上一篇表格操作为基础,加入分页操作,完善核心代码。上篇详情CRUD与文件导入导出

流程

后端开发

1、定义分页查询统一返回的实体类,返回数据为列表,建议使用泛型。

(RespPageEntity.java)

@DatapublicclassRespPageEntity{private List<?> data;private Long total;}

2、定义控制层方法,为避免空值,请求参数中给与默认值。

(UserController.java)

/**
 * 根据页码和大小分页查询
 * @param page 当前页,默认为1
 * @param size 当前每页显示行数,默认为5
 * @return 页信息的实体
 */@GetMapping("/page/")public RespPageEntitygetAllUserByPage(@RequestParam(defaultValue="1") Integer page,@RequestParam(defaultValue="5") Integer size){return userService.getAllUserByPage(page, size);}

3、业务层方法,分为两步,1获取数据总量,2获取查询页信息,因此要加上事务注解@Transactional。

(UserService.java)

@Transactionalpublic RespPageEntitygetAllUserByPage(Integer page, Integer size){
    RespPageEntity pageEntity=newRespPageEntity();// 默认从0开始if(page!= null&& size!= null){
        page=(page-1)*size;}// 获取当前也用户信息
    List<User> users=  userMapper.getAllUserByPage(page, size);
    pageEntity.setData(users);// 获取当前用户总量
    Long total= userMapper.getTotal();
    pageEntity.setTotal(total);return pageEntity;}

4、映射文件中的sql语句。

(UserMapper.xml)

<selectid="getAllUserByPage"resultMap="BaseResultMap">
  select
    *
  FROM
    userinfo
  limit #{page}, #{size}</select><selectid="getTotal"resultType="java.lang.Long">
  select count(*) from userinfo;</select>

5、postman测试,如地址http://127.0.0.1:8081/user/page/返回默认值或http://127.0.0.1:8081/user/page/?page=1&size=5

前端完善

1、template临时组件中加入分页的div(User.vue)

<div style="display: flex;justify-content: center;margin-top: 10px">
  <el-pagination
    background
    @size-change="sizeChange"
    @current-change="currentChange"
    :current-page="currentPage"
    :page-size="pageSize"
    layout="sizes, prev, pager, next, jumper, ->, total, slot"
    :total="total">
  </el-pagination>
</div>

2、初始值

pageSize:5,
currentPage:1,
total:0,

3、每页显示的数量和当前页码

sizeChange(size){this.pageSize=size;this.initUser();},currentChange(page){this.currentPage=page;this.initUser();},

4、修改初始化页面方法

initUser() {
  this.getRequest("/user/page/?page="+this.currentPage+"&size="+this.pageSize).then(resp => {
    if (resp) {
      this.userinfo=resp.data;
      this.total=resp.total;
    }
  })
}

运行后效果图
SpringBoot+Vue之分页操作

  • 作者:永动的图灵机
  • 原文链接:https://blog.csdn.net/weixin_40141790/article/details/89645500
    更新时间:2022年11月4日08:29:24 ,共 1953 字。