vue的分页怎么实现
Vue 分页实现方法
在 Vue 中实现分页功能通常需要结合前端分页逻辑和后端 API 支持。以下是几种常见的实现方式:
前端分页实现(适合数据量较小的情况)
数据全部加载到前端后,通过计算属性或方法实现分页:

<template>
<div>
<table>
<!-- 表格内容 -->
</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 {
data() {
return {
allData: [], // 所有数据
currentPage: 1,
pageSize: 10
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.pageSize)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>
后端分页实现(推荐用于大数据量)
通过 API 请求获取分页数据:

<template>
<div>
<table>
<!-- 使用 paginatedData 渲染表格 -->
</table>
<div class="pagination">
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="fetchData(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
paginatedData: [],
currentPage: 1,
totalPages: 1,
pageSize: 10
}
},
methods: {
async fetchData(page) {
const response = await axios.get(`/api/data?page=${page}&size=${this.pageSize}`)
this.paginatedData = response.data.items
this.totalPages = response.data.totalPages
this.currentPage = page
}
},
created() {
this.fetchData(1)
}
}
</script>
使用第三方分页组件
许多 UI 库提供了现成的分页组件,例如 Element UI 的 Pagination:
<template>
<div>
<el-table :data="tableData"></el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
async fetchData() {
const res = await axios.get(`/api/data?page=${this.currentPage}&size=${this.pageSize}`)
this.tableData = res.data.items
this.total = res.data.total
}
}
}
</script>
分页样式优化
可以添加 CSS 美化分页控件:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
color: #ccc;
cursor: not-allowed;
}
以上方法可根据实际项目需求选择使用。前端分页适合数据量小的场景,后端分页更适合处理大量数据。第三方组件可以快速实现功能,但可能需要进行样式定制。






