vue实现分页页码
实现分页页码的基本思路
在Vue中实现分页页码功能,通常需要结合后端API返回的分页数据(如总页数、当前页码等)和前端逻辑。核心是通过计算属性动态生成页码数组,并处理页码切换事件。
基础实现步骤
模板部分
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span
v-for="page in displayedPages"
:key="page"
@click="goToPage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
脚本部分
<script>
export default {
props: {
totalItems: Number, // 总数据量
itemsPerPage: Number, // 每页条数
currentPage: Number // 当前页码
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
displayedPages() {
const range = 2; // 显示前后页码范围
const pages = [];
for (let i = Math.max(1, this.currentPage - range);
i <= Math.min(this.currentPage + range, this.totalPages);
i++) {
pages.push(i);
}
return pages;
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.$emit('page-change', this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.$emit('page-change', this.currentPage + 1);
}
},
goToPage(page) {
this.$emit('page-change', page);
}
}
};
</script>
高级优化方案
添加省略号效果 当页码较多时,可通过判断添加省略号:
displayedPages() {
const range = 2;
const pages = [];
const start = Math.max(1, this.currentPage - range);
const end = Math.min(this.currentPage + range, this.totalPages);
if (start > 1) pages.push(1, '...');
for (let i = start; i <= end; i++) pages.push(i);
if (end < this.totalPages) pages.push('...', this.totalPages);
return pages.filter((page, index, array) =>
page !== '...' || array[index] !== array[index + 1]
);
}
处理省略号点击
goToPage(page) {
if (page === '...') return;
this.$emit('page-change', page);
}
样式建议
.pagination {
display: flex;
gap: 8px;
}
.pagination button {
padding: 4px 8px;
}
.pagination span {
padding: 4px 8px;
cursor: pointer;
}
.pagination .active {
font-weight: bold;
color: blue;
}
组件使用示例
<Pagination
:total-items="100"
:items-per-page="10"
:current-page="currentPage"
@page-change="handlePageChange"
/>
注意事项
- 分页组件应设为无状态组件,通过props接收数据
- 页码切换事件通过
$emit通知父组件 - 对于大型数据集,建议使用虚拟滚动代替传统分页
- 移动端可考虑添加手势滑动支持







