前端js的資料純前端分頁通用方法封裝
阿新 • • 發佈:2022-03-31
通常開發專案當中,我們需要用到的表格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); } returndataSource; }
然後,引入方法
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'},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) },
{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 {
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最後一頁和第一頁的邏輯判斷,可以根據不同的業務需求改變所需的業務邏輯