Vue3配合MybatisPlus实现分页逻辑
1.后端代码:
例如要实现一个商品的分页查询:要求前端传回的参数,只需要当前页,和页面显示limit 这两个数据最好都设置默认值。
@GetMapping("/productList")
public Result productList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
List<Products> list;
ProductPage productPage = null;
try {
// 设置分页参数
PageParams pageParams = new PageParams();
pageParams.setPageNum(pageNum);
pageParams.setPageSize(pageSize);
PageHelper.startPage(pageParams.getPageNum(), pageSize);
List<Products> products = productsMapper.selectList(null);
PageInfo<Products> pageInfo = new PageInfo<>(products);
int pages = pageInfo.getPages();
int pageNum1 = pageInfo.getPageNum();
list = pageInfo.getList();
productPage = new ProductPage();
productPage.setProductsList(list);
productPage.setPageNum(pageNum1);
productPage.setPages(pages);
} catch (Exception ignored) {
}
return Result.success(productPage);
}
使用的pageHelper插件实现的分页,插件可以根据我们设置的限制动态计算出总页码,也可以直接取出来当前页,下一页的索引。
2.Vue3 对应的代码:
<!-- 检查当前页码是否大于1 -->
<a class="btn btn-outline-primary" v-if="currentPage > 1" @click="prevPage">上一页</a>
<!-- 检查当前页码是否小于总页数 -->
<a class="btn btn-outline-primary" @click="nextPage">下一页</a>
这个例子是 根据当前页的,来设置是显示上一页还是下一页。
在这个前端的组件页面上,在这个组件的挂载的生命周期,先实现表格数据的渲染默认是第一页的数据,当点击上一页和下一页时:
getProductList 方法是对应的后端的分页方法,在这里当后端传回来数据后这里使用的是currentPage的值是++,最好使用后端传回来的数据。
// / 上一页逻辑
const prevPage = async () => {
if (currentPage.value > 1) {
const res= await getProductList(currentPage.value - 1);
// 更新当前页码
currentPage.value--;
productItemList.splice(
0,
productItemList.length,
...res.data.data.productsList
);
}
};
// 下一页逻辑
const nextPage = async () => {
if (currentPage.value < totalPage.value) {
const res= await getProductList(currentPage.value +1);
// 更新当前页码
currentPage.value++;
productItemList.splice(
0,
productItemList.length,
...res.data.data.productsList
);
}
};