vue实现分页功能
Vue 分页功能实现
基础分页逻辑
分页功能通常需要以下核心数据:
currentPage: 当前页码pageSize: 每页显示条目数total: 总数据量
计算总页数公式: \( totalPages = Math.ceil(total / pageSize) \)
前端实现方案
模板部分
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100,
allData: [] // 原始数据
}
},
computed: {
totalPages() {
return Math.ceil(this.total / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
}
}
</script>
后端API配合
典型的分页API参数:
page: 请求的页码limit: 每页数据量
响应数据结构建议包含:
{
"data": [],
"total": 100,
"page": 1,
"limit": 10
}
组件化实现
可封装为可复用分页组件:
<!-- Pagination.vue -->
<template>
<div class="pagination">
<button @click="$emit('page-change', currentPage - 1)"
:disabled="currentPage <= 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button @click="$emit('page-change', page)"
:class="{ active: page === currentPage }">
{{ page }}
</button>
</span>
<button @click="$emit('page-change', currentPage + 1)"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
</template>
第三方库方案
常用分页库:
vue-paginateelement-ui pagination(适合Element用户)v-pagination
以element-ui为例:
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
性能优化建议
大数据量时避免前端分页,推荐后端分页 使用虚拟滚动技术处理超长列表 添加分页加载动画提升用户体验
样式定制技巧
通过CSS变量自定义分页样式:

.pagination {
--active-color: #42b983;
--hover-color: #f0f0f0;
}
.pagination button.active {
background-color: var(--active-color);
}
移动端适配
简化移动端分页控件 添加滑动加载更多功能 使用响应式布局调整按钮大小






