vue 实现表格分页
Vue 实现表格分页的方法
使用 Element UI 的分页组件
Element UI 提供了现成的分页组件 el-pagination,可以快速实现表格分页功能。以下是一个完整的示例代码:

<template>
<div>
<el-table :data="tableData" border>
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
: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
const mockData = [] // 这里应该是你的实际数据
this.tableData = mockData.slice(start, end)
this.total = mockData.length
}
},
created() {
this.fetchData()
}
}
</script>
自定义分页实现
如果不使用UI框架,可以手动实现分页功能。核心逻辑是根据当前页码和每页显示数量计算显示的数据范围。

<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === pageCount">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPage: 1,
pageSize: 5
}
},
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: {
prevPage() {
this.currentPage--
},
nextPage() {
this.currentPage++
}
},
created() {
// 获取数据
this.allData = [...]
}
}
</script>
与后端API配合
实际项目中通常需要从后端API获取分页数据。以下是配合后端API的实现方式:
methods: {
async fetchData() {
try {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.tableData = res.data.items
this.total = res.data.total
} catch (error) {
console.error(error)
}
}
}
分页样式优化
可以添加一些CSS样式来美化分页组件:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法涵盖了从简单到复杂的分页实现方案,可以根据项目需求选择合适的实现方式。






