vue实现表格页面分页
Vue实现表格分页的方法
使用Element UI的el-pagination组件
安装Element UI库后,可以直接使用其分页组件。表格数据通过current-page和page-size控制分页。
<template>
<div>
<el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 50, 100]"
: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
},
handleCurrentChange(val) {
this.currentPage = val
}
}
}
</script>
自定义分页逻辑
不使用UI库时,可以手动实现分页功能。通过计算属性获取当前页数据。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<!-- 表格内容 -->
</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 {
tableData: [],
currentPage: 1,
pageSize: 10
}
},
computed: {
pageCount() {
return Math.ceil(this.tableData.length / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
后端分页实现
当数据量很大时,建议采用后端分页。通过API传递分页参数,获取当前页数据。
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
}
axios.get('/api/data', { params })
.then(response => {
this.tableData = response.data.items
this.total = response.data.total
})
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
分页样式优化
可以添加CSS美化分页控件,使其更符合项目风格。
.pagination {
margin-top: 20px;
text-align: center;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据项目需求选择适合的实现方式。Element UI等组件库提供了开箱即用的解决方案,而自定义分页则更灵活。后端分页适合大数据量场景,能显著提升性能。







