vue实现页面组件分页
实现分页的基本思路
在Vue中实现分页功能,通常需要结合后端API返回的分页数据和前端组件展示。分页的核心逻辑包括计算总页数、当前页数据切片、页码切换事件处理等。
分页组件封装
创建一个可复用的分页组件,包含页码按钮、上一页/下一页按钮和跳转功能:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</span>
<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>
列表组件集成
在列表组件中使用分页组件,处理数据分页逻辑:

<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<pagination
:total-items="items.length"
:items-per-page="itemsPerPage"
:current-page="currentPage"
@page-changed="onPageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
items: [], // 从API获取的全部数据
itemsPerPage: 10,
currentPage: 1
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
onPageChange(page) {
this.currentPage = page
}
}
}
</script>
后端API分页
实际项目中更常见的做法是通过API实现服务端分页:
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
}
高级分页优化
对于大量数据的分页显示,可以添加以下优化:

添加页码省略功能,当页数过多时显示部分页码:
pages() {
const range = []
const maxVisible = 5
let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2))
let end = Math.min(this.totalPages, start + maxVisible - 1)
if (end - start + 1 < maxVisible) {
start = Math.max(1, end - maxVisible + 1)
}
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
添加跳转输入框:
<input
type="number"
v-model.number="inputPage"
min="1"
:max="totalPages"
@keyup.enter="goToPage"
>
<button @click="goToPage">跳转</button>
样式处理
为分页组件添加基础样式:
.pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #42b983;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






