vue实现分页按钮
实现分页按钮的基本思路
在Vue中实现分页按钮需要结合数据绑定和事件处理。通常需要一个当前页码(currentPage)和总页数(totalPages)的状态,通过计算属性或方法生成页码数组,并用v-for渲染按钮。
定义数据与计算属性
data() {
return {
currentPage: 1,
totalItems: 100,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
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;
}
}
模板渲染
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<button
v-for="page in pages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
方法实现
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page;
this.$emit('page-changed', page); // 可选:触发父组件事件
}
}
}
样式优化
添加CSS增强交互体验:
.pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination button:hover:not(:disabled) {
background: #eee;
}
.pagination button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级功能扩展
对于大量数据的分页,可以添加省略号逻辑:
computed: {
pages() {
const range = [];
const delta = 2;
const left = this.currentPage - delta;
const right = this.currentPage + delta;
for (let i = 1; i <= this.totalPages; i++) {
if (
i === 1 ||
i === this.totalPages ||
(i >= left && i <= right) ||
(i === left - 1 && left > 2) ||
(i === right + 1 && right < this.totalPages - 1)
) {
range.push(i);
} else if (range[range.length - 1] !== '...') {
range.push('...');
}
}
return range;
}
}
模板中需要对应处理省略号:

<template>
<span v-if="page === '...'">...</span>
<button v-else ...></button>
</template>





