一、 前言
分页对于前端开发而言,是一个经常遇见也比较简单的功能。常见的处理方式是结合后端接口处理即可。
但偶尔有时候后端接口不太方便提供该功能时,我们可以自己通过前端实现一个假的分页效果!
二、实现代码
其主要实现和传统的分页(如element提供的分页组件)区别在于对 current-change(页码)改变时的处理
- 传统分页:在
current-change
回调时间中,拿到最新的页码,重新请求接口即可 - 自己实现假分页:在
current-change
回调时间中,拿到最新的页码,去从所以的列表数据中截取出对应的数据
代码实现
// changePagination 是 current-change 的回调函数
changePagination({currentPage}) {
// 保存最新的页码
this.tablePage.currentPage = currentPage;
// 如果是第一页,则截取0到pageSize(每页显示多少条数据)即可
if (currentPage == 1) {
this.showUserList = this.tableData.slice(0, this.tablePage.pageSize);
return;
}
// 当前页 - 1 * 页数 = 分割开始数 比如二页 - 1 = 1*page
const startSize = (currentPage - 1) * this.tablePage.pageSize;
// 分割结束数 = 分割开始数 + this.pageSize
this.showUserList = this.tableData.slice(startSize, startSize + this.tablePage.pageSize);
// 如果处理后没有数据(删除了最后一页所有数据),则往前处理一页
if(!this.showUserList.length && currentPage > 1) {
this.changePagination({currentPage: this.tablePage.currentPage - 1});
}
},
文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!