1、通过PageHelper实现数据分页查询(SpringBoot+Mabatis)。首先,在pom.xml中导入pagehelper相关依赖。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2、接下来将进行后端Java代码的介绍,此处以用户的查询操作为例进行实现。新建一个Page对象,用于接收前端通过POST请求传递过来的JSON数据。
package com.fl.domain;
public class Page {
private Integer pageSize;
private Integer pageNum;
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
@Override
public String toString() {
return "Page{" +
"pageSize=" + pageSize +
", pageNum=" + pageNum +
'}';
}
}
3、新建getAll()方法用于查询。PageHelper.startPage(pageNum, pageSize)用于开启分页,并设置当前页面索引以及每页所显示的数据数量。调用service层中的getAll方法,并将接收到的数据转换为PageInfo,并封装成Result类返回。(Dao层和Service层代码不做详细说明,普通的查询全部数据即可。)
@PostMapping("/getAll")
public Result getAll(@RequestBody Page page) {
PageHelper.startPage(page.getPageNum(), page.getPageSize());
List<User> users = userService.getAll();
PageInfo<User> userPageInfo = new PageInfo<>(users);
Integer code = users != null ? Code.GET_SUCC : Code.GET_ERR;
String msg = users != null ? "查询数据成功!" : "查询数据失败,请重试!";
return new Result(code, userPageInfo, msg);
}
4、接下来进行前端代码的书写。首先,添加elementUI分页组件。page-size用于设置页面数据量,current-page用于设置当前页码索引,@size-change设置尺寸改变方法,@current-change设置页码改变方法。
<el-pagination
:page-sizes="[5, 10, 15, 20]"
:page-size="pageSize"
:current-page="currentPage"
layout="total, sizes, prev, pager, next, jumper"
:total=count
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
>
</el-pagination>
export default {
name: "User",
components: {AddUser},
data() {
return {
tableData: [],
deleteIds: [],
count: 0,
pageSize: 10,
currentPage: 1,
}
},
methods: {
// 获取全部用户信息
getUsers() {
api.getUers({pageNum: this.currentPage, pageSize: this.pageSize}).then(res => {
console.log(res)
this.count = res.data.total
this.tableData = res.data.list
})
},
handleSizeChange(val) {
this.pageSize = val
this.getUsers()
},
handleCurrentChange(val) {
this.currentPage = val
this.getUsers()
}
},
created() {
this.getUsers()
},
}
最终实现效果如下: