vue表格分页如何实现
实现Vue表格分页的方法
在Vue中实现表格分页通常需要结合前端分页逻辑和后端API分页请求。以下是两种常见的实现方式:
前端分页实现
适用于数据量较小的情况,所有数据一次性加载到前端后通过计算属性分页。
模板部分
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</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 {
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: {
prevPage() {
this.currentPage--
},
nextPage() {
this.currentPage++
}
}
}
</script>
后端分页实现
适用于大数据量场景,每次只请求当前页的数据。
模板部分
<template>
<div>
<table>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.name }}</td>
<!-- 其他列 -->
</tr>
</table>
<div class="pagination">
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="fetchData(currentPage + 1)" :disabled="!hasNextPage">下一页</button>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
totalItems: 0
}
},
computed: {
hasNextPage() {
return this.currentPage * this.pageSize < this.totalItems
}
},
methods: {
async fetchData(page) {
try {
const response = await api.get('/data', {
params: {
page,
size: this.pageSize
}
})
this.tableData = response.data.items
this.totalItems = response.data.total
this.currentPage = page
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData(1)
}
}
</script>
使用第三方组件库
流行的UI库如Element UI、Ant Design Vue等提供了现成的分页组件:
Element UI示例
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<!-- 其他列 -->
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</template>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
}
</script>
分页样式优化
可以添加CSS改善分页控件外观:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
以上方法可根据实际项目需求选择使用,大数据量推荐后端分页,小数据量前端分页更简单高效。







