vue 实现表格分页
实现表格分页的方法
使用Element UI的el-pagination组件
安装Element UI依赖后,在Vue组件中引入表格和分页组件。通过v-model绑定当前页码和每页条数,监听current-change和size-change事件更新数据。
<template>
<div>
<el-table :data="tableData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 模拟API请求
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
this.tableData = allData.slice(start, end);
this.total = allData.length;
}
},
mounted() {
this.fetchData();
}
}
</script>
手动实现分页逻辑
不依赖UI库时,可通过计算属性实现分页功能。定义当前页码和每页条数,利用数组切片方法过滤数据。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<!-- 表格内容 -->
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage >= pageCount">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 全部数据
currentPage: 1,
pageSize: 10
}
},
computed: {
pageCount() {
return Math.ceil(this.allData.length / this.pageSize);
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
methods: {
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++;
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
}
</script>
与后端API配合
实际项目中通常需要后端分页支持。通过axios发送请求时携带页码和每页条数参数,后端返回对应数据及总条数。
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.tableData = response.data.items;
this.total = response.data.total;
});
}
}
关键注意事项
- 分页器需显示总条数(total)和总页数计算
- 当前页码变化时需重新获取数据
- 每页条数变化时应重置当前页码为1
- 前端分页仅适合数据量较小的情况,大数据量需后端分页







