Vue+Element-UI 实现前端分页功能,利用el-table和el-pagination组件实现表格前端分页:
????????当table的数据量比较大的时候,一个屏幕展示不出全部的数据,这个时候就需要分页显示。而多数情况下都是做的后端分页,就是将分页参数和查询条件一并传到后端,后端将当前页要显示的数据返回来。但是有时候会遇到后端也是去调用了其它系统的接口,这时候返回到前端的是所有的数据,此时需要前端自行去进行分页显示。今天抽空写了个demo,效果如下:
有朋友要用el-table组件做前端分页的时候可以参考以下代码:
<template>
??<div?class="paging">
????<div?class="box_body">
??????<el-table?:data="tableData"?border?size="small"?style="width:?100%">
????????<el-table-column
??????????label="序号"
??????????prop="num"
??????????min-width="150"
????????></el-table-column>
????????<el-table-column
??????????label="姓名"
??????????prop="name"
??????????min-width="150"
????????></el-table-column>
????????<el-table-column
??????????label="性别"
??????????prop="sex"
??????????min-width="150"
????????></el-table-column>
????????<el-table-column
??????????label="年龄"
??????????prop="age"
??????????min-width="150"
????????></el-table-column>
??????</el-table>
??????<!--===分页=====-->
??????<el-pagination
????????:current-page="pageinfo.page"
????????:page-sizes="[10,?20,?30,?40]"
????????:page-size="pageinfo.size"
????????layout="total,?sizes,?prev,?pager,?next,?jumper"
????????:total="pageinfo.total"
????????@size-change="handleSizeChange"
????????@current-change="handleCurrentChange"
????????style="margin-bottom:?3px"
??????></el-pagination>
????</div>
??</div>
</template>
<script>
export?default?{
??name:?"paging",
??data()?{
????return?{
??????//?从后端获取到的所有表格数据
??????sourceTableData:?[],
??????//?页面要显示的表格数据
??????tableData:?[],
??????//?分页信息
??????pageinfo:?{
????????page:?1,
????????size:?10,
????????total:?0,
??????},
????};
??},
??created()?{
????//?页面初始化时生成100条数据,模拟从后端获取所有数据
????let?arr?=?[];
????for?(let?i?=?0;?i?<?100;?i++)?{
??????let?obj?=?{};
??????obj.num?=?i?+?1;
??????obj.name?=?"name"?+?(i?+?1);
??????obj.sex?=?Math.round(Math.random())?==?0???"男"?:?"女";
??????obj.age?=?20?+?Math.round(Math.random()?*?30);
??????arr.push(obj);
????}
????this.sourceTableData?=?arr;
????//?初始化算出第一页数据
????this.tableData?=?this.currentChangePage(
??????this.pageinfo.size,
??????this.pageinfo.page
????);
????this.pageinfo.total?=?this.sourceTableData.length;
??},
??methods:?{
????/**?切换每页显示条数?*/
????handleSizeChange(val)?{
??????this.pageinfo.page?=?1;
??????this.pageinfo.size?=?val;
??????this.tableData?=?this.currentChangePage(val,?this.pageinfo.page);
????},
????/**?切换分页?*/
????handleCurrentChange(val)?{
??????this.pageinfo.page?=?val;
??????this.tableData?=?this.currentChangePage(this.pageinfo.size,?val);
????},
????//?分页方法(用于表格数据后端不分页,放到前端做分页)
????currentChangePage(size,?current)?{
??????const?tablePush?=?[];
??????let?array?=?JSON.parse(JSON.stringify(this.sourceTableData));
??????array.forEach((item,?index)?=>?{
????????if?(size?*?(current?-?1)?<=?index?&&?index?<=?size?*?current?-?1)?{
??????????tablePush.push(item);
????????}
??????});
??????return?tablePush;
????},
??},
};
</script>
<style>
.paging?{
??width:?100%;
??height:?100%;
}
.box_body?{
??width:?1200px;
??margin:?50px?auto;
}
</style>