vue完整实现分页
实现分页的基本思路
在Vue中实现分页功能通常需要结合后端API和前端组件。后端负责提供分页数据,前端负责展示分页控件和处理用户交互。以下是完整实现分页的步骤:
后端API设计
后端需要提供支持分页的API接口,通常包含以下参数:

page: 当前页码pageSize: 每页显示数量total: 总记录数
返回数据结构示例:
{
"data": [...], // 当前页数据
"total": 100, // 总记录数
"page": 1, // 当前页码
"pageSize": 10 // 每页数量
}
前端组件实现
分页组件封装
<template>
<div class="pagination">
<button
:disabled="currentPage === 1"
@click="changePage(currentPage - 1)"
>
上一页
</button>
<span v-for="page in pages" :key="page">
<button
:class="{ active: currentPage === page }"
@click="changePage(page)"
>
{{ page }}
</button>
</span>
<button
:disabled="currentPage === totalPages"
@click="changePage(currentPage + 1)"
>
下一页
</button>
<span>共 {{ total }} 条</span>
</div>
</template>
<script>
export default {
props: {
total: {
type: Number,
required: true
},
currentPage: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.total / this.pageSize)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-change', page)
}
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
使用分页组件
<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<!-- 其他列 -->
</tr>
</table>
<pagination
:total="total"
:current-page="currentPage"
:page-size="pageSize"
@page-change="handlePageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
items: [],
total: 0,
currentPage: 1,
pageSize: 10
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
// 调用API获取数据
api.getItems({
page: this.currentPage,
pageSize: this.pageSize
}).then(response => {
this.items = response.data
this.total = response.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
}
</script>
高级分页功能
分页优化
对于大量数据,可以优化分页显示,只显示当前页附近的页码:

pages() {
const range = []
const start = Math.max(1, this.currentPage - 2)
const end = Math.min(this.totalPages, this.currentPage + 2)
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
分页与路由结合
可以将当前页码保存在路由参数中,实现浏览器前进后退功能:
methods: {
handlePageChange(page) {
this.$router.push({
query: { ...this.$route.query, page }
})
}
},
watch: {
'$route.query.page'(page) {
this.currentPage = Number(page) || 1
this.fetchData()
}
}
分页组件库
也可以直接使用现成的分页组件库,如Element UI的Pagination:
<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</template>
以上是Vue中实现分页功能的完整方案,可以根据项目需求选择合适的实现方式。





