vue实现表格分页组件
Vue 表格分页组件实现
数据准备与分页逻辑
在Vue组件中定义表格数据和分页相关变量:
data() {
return {
tableData: [], // 表格数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
total: 0 // 总数据量
}
}
计算属性实现分页数据切片:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
}
模板结构
使用element-ui或自定义模板结构:
<template>
<div>
<table>
<tr v-for="(item, index) in paginatedData" :key="index">
<!-- 表格内容渲染 -->
</tr>
</table>
<!-- 分页控件 -->
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第{{ currentPage }}页</span>
<button @click="nextPage" :disabled="currentPage >= pageCount">下一页</button>
<select v-model="pageSize" @change="handleSizeChange">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
</div>
</div>
</template>
方法实现
添加分页控制方法:
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++
}
},
handleSizeChange() {
this.currentPage = 1 // 重置页码
},
// 计算总页数
get pageCount() {
return Math.ceil(this.total / this.pageSize)
}
}
使用Element UI组件
若使用Element UI可简化实现:
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[5, 10, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next"
:total="total">
</el-pagination>
对应方法:
handleSizeChange(val) {
this.pageSize = val
},
handleCurrentChange(val) {
this.currentPage = val
}
样式优化
添加基础分页样式:
.pagination {
margin-top: 20px;
display: flex;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
注意事项
- 异步数据加载需在获取数据后更新total值
- 大型数据集建议使用服务器端分页
- 可添加页码跳转功能增强用户体验
- 移动端需调整分页控件布局






