vue 分页的实现
分页组件的实现
在Vue中实现分页功能,通常需要结合后端API返回的分页数据。以下是一个常见的分页组件实现方式。
模板部分
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<span
v-for="page in pages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
脚本部分
<script>
export default {
props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
}
},
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
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
分页数据获取
在实际应用中,通常需要从API获取分页数据。以下是一个示例:
methods: {
async fetchData(page = 1) {
try {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData()
}
分页样式
为分页组件添加基本样式:
<style scoped>
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button, .pagination span {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
border: 1px solid #ddd;
background: #fff;
}
.pagination span.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
</style>
分页逻辑优化
对于大型数据集,可以考虑添加以下优化:
- 添加页面跳转输入框
- 显示总页数和当前页码
- 添加首尾页跳转按钮
- 实现动态页码范围计算
computed: {
showStartEllipsis() {
return this.currentPage > 3
},
showEndEllipsis() {
return this.currentPage < this.totalPages - 2
}
}
第三方分页组件
也可以考虑使用现成的分页组件库:

vue-paginatev-paginationelement-ui的el-paginationvuetify的v-pagination
这些组件提供了更丰富的功能和更好的可定制性。






