vue中分页的实现
分页组件实现
在Vue中实现分页通常需要结合后端API的分页数据,前端处理分页逻辑并渲染分页器。以下是两种常见实现方式:
基础分页组件
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in pages" :key="page">
<button
@click="goToPage(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: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
},
goToPage(page) {
this.$emit('page-changed', page)
}
}
}
</script>
结合API请求的分页
父组件调用示例

<template>
<div>
<data-table :items="items" />
<pagination
:total-items="totalItems"
:items-per-page="10"
:current-page="currentPage"
@page-changed="fetchData"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
items: [],
totalItems: 0,
currentPage: 1
}
},
mounted() {
this.fetchData(1)
},
methods: {
async fetchData(page) {
const response = await axios.get('/api/items', {
params: { page, limit: 10 }
})
this.items = response.data.items
this.totalItems = response.data.total
this.currentPage = page
}
}
}
</script>
使用第三方库
对于复杂分页需求,可以考虑使用现成的分页组件库:
Element UI分页

<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next"
@current-change="handlePageChange"
/>
Vuetify分页
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
></v-pagination>
分页样式优化
添加CSS样式增强分页器视觉效果:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上实现方案可根据实际项目需求进行调整,关键点在于维护当前页码状态、计算总页数并通过事件通知父组件页码变化。






