vue实现前端分页
Vue 前端分页实现方法
基础数据分页
-
准备分页数据
data() { return { allItems: [], // 原始数据 currentPage: 1, // 当前页码 itemsPerPage: 10 // 每页条数 } } -
计算分页数据
computed: { paginatedItems() { const start = (this.currentPage - 1) * this.itemsPerPage const end = start + this.itemsPerPage return this.allItems.slice(start, end) }, totalPages() { return Math.ceil(this.allItems.length / this.itemsPerPage) } } -
分页控件模板
<template> <div> <ul> <li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li> </ul> <div class="pagination"> <button @click="prevPage" :disabled="currentPage === 1">上一页</button> <span>{{ currentPage }} / {{ totalPages }}</span> <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button> </div> </div> </template>
高级分页组件
-
创建可复用分页组件
// Pagination.vue props: { totalItems: Number, itemsPerPage: Number, currentPage: Number }, computed: { totalPages() { return Math.ceil(this.totalItems / this.itemsPerPage) } }, methods: { changePage(page) { this.$emit('page-changed', page) } } -
使用分页组件

<pagination :total-items="allItems.length" :items-per-page="itemsPerPage" :current-page="currentPage" @page-changed="currentPage = $event" />
分页样式优化
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
分页逻辑优化
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
goToPage(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page
}
}
}
带页码显示的分页
<div class="page-numbers">
<span
v-for="page in totalPages"
:key="page"
@click="goToPage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</span>
</div>
与后端API结合
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.allItems = response.data.items
this.totalItems = response.data.total
}
这些方法可以根据实际需求组合使用,实现从简单到复杂的前端分页功能。






