前端js的数据纯前端分页通用方法封装
通常开发项目当中,我们需要用到的表格table数据,一般在接口都会做分页,但也会存在某些情况,比如我们在大屏幕中需要展示某些数据,但是接口数据是一次性全部返回,且要求页面为了美观只能展示指定个数的请求下,我们会需要做分页来处理,那么我们就需要写一个方法来做纯前端分页,所幸,本人在项目中实践过,所以就封装了一个方法,看起来是比较通用的。
那么,我们开始吧!!!
首先,封装的方法
/** * 前端分页,不再次请求接口,不破坏原数组list * @param list 请求接口返回的全部数据 * @param pageSize 一页展示的数据个数 * @param currentPage 当前页码 * @returns [] */ export function getPagination (list, pageSize, currentPage) { let dataSource = []; if (list.length < pageSize) { //判断当前获取的接口数据的长度是否大于设置的展示个数(总页数是否大于1) const index = (currentPage - 1) * pageSize; dataSource = list.slice(index, pageSize);//截取当页展示数据 } else if (currentPage === Math.ceil(list.length / pageSize)) { //当前页码是否为最后一页 const index = (currentPage - 1) * pageSize; dataSource = list.slice(index); } else { /** * 若总页数大于1,且当前页码不是最后一页时 * 获取下标(index)截取数据(dataSource) */ const index = (currentPage - 1) * pageSize; dataSource = list.slice(index, currentPage * pageSize); } return dataSource; }
然后,引入方法
import { getPagination } from './pagination';
调用方法,实现分页展示效果
export default { name:'TableData', data(){ return{ list:[],// 总数据 pageSize:5,// 当前页码数据个数 currentPage:1,// 当前页码 total:0,// 总条数 dataSource:[],// 展示的数据 size:0// 总页数 } }, methods:{ getList(){ this.list=[ // 接口请求数据 {id:1,name:'index_1'},
{id:2,name:'index_2'},
{id:3,name:'index_3'},
{id:4,name:'index_4'},
{id:5,name:'index_5'},
{id:6,name:'index_6'},
{id:7,name:'index_7'},
{id:8,name:'index_8'} ] this.size=Math.ceil(this.list.length / this.pageSize);// 向上取整 this.dataSource = getPagination( this.list, this.pageSize, this.currentPage ); }, currentPageChange(type,current){ // 当前页码切换 if(current){ this.currentPage=current
}else {
if (type === 'right') {
if (this.currentPage < this.size && this.currentPage > 0) {
this.currentPage = this.currentPage + 1;
} else if (this.currentPage === this.size) {
this.$message.warn('已经到最后了');
return false;
}
} else {
if (this.currentPage > 1) {
this.currentPage = this.currentPage - 1;
} else if (this.currentPage === 1) {
this.$message.warn('已经是第一页了');
return false;
}
}
}
this.dataSource = getPagination(
this.list,
this.pageSize,
this.currentPage)
},
pageSizeChange(pageSize){ // pageSize改变 if(pageSize){ this.pageSize = pageSize this.dataSource = getPagination( this.list, this.pageSize, this.currentPage ); } } } }
展示数据用法
<div v-for="item in baseInfo" :key="item.id"> <span>{{item.name}}</span> </div> <div> <a-icon type="left" @click="currentPageChange('left')" />
<a-icon type="right" @click="currentPageChange('right')" />
<a-select @change="pageSizeChange" :value="pageSize" style="width: 120px">
<a-select-option :value="5">5</a-select-option>
<a-select-option :value="10">10</a-select-option>
<a-select-option :value="20">20</a-select-option>
<a-select-option :value="50">50</a-select-option>
</a-select>
</<div>
需要注意的是,currentPage最后一页和第一页的逻辑判断,可以根据不同的业务需求改变所需的业务逻辑

浙公网安备 33010602011771号