vue实现分页组件思路
基础分页组件实现
创建一个基础分页组件需要定义当前页码、总页数、页码按钮等核心功能。使用v-for渲染页码按钮,通过v-model或props管理当前页状态。
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in pages"
:key="page"
@click="changePage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
<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)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
this.$emit('page-changed', page)
},
prevPage() {
if (this.currentPage > 1) {
this.$emit('page-changed', this.currentPage - 1)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.$emit('page-changed', this.currentPage + 1)
}
}
}
}
</script>
优化页码显示逻辑
当页码过多时,需要优化显示方式,常见方案是显示当前页前后几页,并用省略号表示跳页。

computed: {
pages() {
const current = this.currentPage
const total = this.totalPages
const range = []
// 总页数<=7时显示全部
if (total <= 7) {
for (let i = 1; i <= total; i++) {
range.push(i)
}
}
// 其他情况使用智能截断
else {
const left = Math.max(2, current - 2)
const right = Math.min(total - 1, current + 2)
range.push(1)
if (left > 2) range.push('...')
for (let i = left; i <= right; i++) {
range.push(i)
}
if (right < total - 1) range.push('...')
range.push(total)
}
return range
}
}
集成到数据列表
将分页组件与数据列表结合使用,通常需要计算当前页的数据切片。

computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
}
}
添加自定义配置项
通过props允许自定义每页显示数量、可见页码数等参数,增强组件灵活性。
props: {
totalItems: Number,
itemsPerPage: {
type: Number,
default: 10
},
visiblePages: {
type: Number,
default: 5
},
currentPage: {
type: Number,
default: 1
}
}
样式优化建议
为分页组件添加基础样式,提升视觉体验。
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






