vue实现分页按钮
Vue 分页按钮实现方法
基础分页组件结构
使用 Vue 的 v-for 渲染页码按钮,结合计算属性动态生成页码范围:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in pageRange"
:key="page"
@click="changePage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
核心计算属性
计算页码范围时考虑当前页位置和最大显示页码数:

computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
pageRange() {
const range = [];
const maxVisible = 5; // 最大可见页码数
let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
const end = Math.min(start + maxVisible - 1, this.totalPages);
start = Math.max(1, end - maxVisible + 1);
for (let i = start; i <= end; i++) {
range.push(i);
}
return range;
}
}
事件处理与方法
实现页码切换和边界检查:

methods: {
changePage(page) {
if (page !== this.currentPage) {
this.currentPage = page;
this.$emit('page-changed', page);
}
},
prevPage() {
if (this.currentPage > 1) {
this.changePage(this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.changePage(this.currentPage + 1);
}
}
}
样式优化
添加基础样式增强交互体验:
.pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
button {
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
button:hover:not(:disabled) {
background: #eee;
}
button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级功能扩展
- 省略号处理
当页码范围不连续时显示省略号:
// 在 computed 中修改 pageRange
if (start > 1) range.unshift('...');
if (end < this.totalPages) range.push('...');
- 动态页码数量
根据屏幕宽度调整可见页码数:
data() {
return {
maxVisible: window.innerWidth < 768 ? 3 : 5
}
},
mounted() {
window.addEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.maxVisible = window.innerWidth < 768 ? 3 : 5;
}
}
- Props 配置
使组件可通过 props 接收外部参数:
props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
}
}
使用示例
在父组件中集成分页控件:
<pagination
:total-items="100"
:items-per-page="10"
:current-page.sync="currentPage"
@page-changed="handlePageChange"
/>






