vue实现表格分页组件
Vue实现表格分页组件的方法
安装依赖(如需要) 若项目未安装Element UI或类似UI库,可通过以下命令安装:
npm install element-ui
基础分页组件结构
使用Element UI的el-pagination组件:
<template>
<div>
<el-table :data="currentPageData">
<!-- 表格列定义 -->
</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: [], // 全部数据
currentPageData: [], // 当前页数据
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.updateCurrentPageData()
},
handleCurrentChange(val) {
this.currentPage = val
this.updateCurrentPageData()
},
updateCurrentPageData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
this.currentPageData = this.tableData.slice(start, end)
},
fetchData() {
// 模拟API请求
this.tableData = Array.from({length: 100}, (_,i) => ({id: i+1}))
this.total = this.tableData.length
this.updateCurrentPageData()
}
},
mounted() {
this.fetchData()
}
}
</script>
自定义样式(可选)
<style scoped>
.el-pagination {
margin-top: 20px;
text-align: right;
}
</style>
纯Vue实现方案(不依赖UI库)
<template>
<div>
<table>
<tr v-for="item in currentPageData" :key="item.id">
<!-- 表格内容 -->
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第{{ currentPage }}页</span>
<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
computed: {
totalPages() {
return Math.ceil(this.tableData.length / this.pageSize)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>
关键点说明
- 分页核心逻辑是通过数组的
slice方法截取当前页数据 currentPage和pageSize变化时需重新计算当前页数据- 分页器事件需绑定
size-change和current-change - 总条目数
total需与后端数据同步(若为异步请求)






