逻辑分页也可以叫做假分页,是将所有数据查询出来再进行分页显示。
逻辑分页
分页有逻辑分页与物理分页之分。
- 物理分页,由后端处理分页数据。适合数据量大的情况。
- 前端查询数据时带上
pageSize
(页面数据量)、currentPage
(当前页码)两个参数,后端根据这两个参数返回相应的数据,直接显示在页面上。案例,见SpringBoot笔记中的“高级查询”。
- 前端查询数据时带上
- 逻辑分页,由前端处理分页数据。适合数据量小的情况。
- 前端查询数据时查询所有的数据,再由前端处理后显示在页面上。
案例
前端
前端源码:
使用VUE
+ElementUI
。el-table
中展示数据。el-pagination
为分页组件。
<template>
<!--表格组件-->
<el-table :data="showTableData" style="width: 100%;">
<el-table-column label="ID" prop="id" width="50">
</el-table-column>
<el-table-column label="采购人ID" prop="user_id" width="150">
</el-table-column>
<el-table-column label="总价格(元)" prop="price" width="150">
</el-table-column>
<el-table-column label="采购时间" prop="buy_time">
</el-table-column>
<el-table-column label="备注" prop="remark" width="525">
</el-table-column>
<el-table-column align="center" width="150" fixed="right">
<template slot="header" slot-scope="scope">
<span>操作</span>
</template>
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)" style="margin-bottom: 5px;">
编辑</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--分页组件-->
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
:page-sizes="[5, 10, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</template>
- 函数
getTableData
,获取全部的数据。 - 函数
showData
用于分页,根据参数currentPage
、pageSize
进行逻辑分页。 - 函数
handleSizeChange
,改变页面显示数量时触发。 - 函数
handleCurrentChange
,切换页面时触发。
当切换页面(currentPage
改变)或改变页面大小(pageSize
改变)时,调用函数showData
,进行分页显示。
//变量
currentPage: 1, //当前的页码
pageSize: 5, //页面大小(每页显示多少条数据)
total: 0, //总数据量
showTableData: [],//显示在页面上的数据
tableData: [], //全部数据
//逻辑分页 相关的几个函数
handleSizeChange(newSize) {
//改变页面显示数量时触发
this.pageSize = newSize;
this.showData(); //更新 显示的数据
},
handleCurrentChange(newPage) {
//切换页面时触发
this.currentPage = newPage;
this.showData(); //更新 显示的数据
},
showData() { //显示数据 将后台获取的全部数据,根据currentPage与pageSize进行显示
this.total = this.tableData.length;
if (this.total > this.currentPage * this.pageSize) {
this.showTableData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
.pageSize);
} else {
this.showTableData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.total);
}
},
//从后端获取数据
getTableData() {
this.$http({
method: 'get',
url: '/record',
responseType: 'json'
})
.then(respon => {
this.tableData = respon.data;//获取全部的数据
this.showData(); //显示数据到页面
})
}
原文链接:逻辑分页