用vue实现分页
使用Vue实现分页功能
分页是Web应用中常见的功能,可以通过Vue结合计算属性和事件处理实现。以下是实现分页的核心步骤:
数据准备 定义数据模型,包括当前页码、每页显示数量和总数据列表:
data() {
return {
currentPage: 1,
itemsPerPage: 10,
allItems: [...], // 你的完整数据数组
}
}
计算当前页数据 使用计算属性筛选当前页显示的数据:
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)
}
}
分页控件模板 在模板中添加分页导航按钮:
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }">
{{ page }}
</span>
<button
@click="currentPage++"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
样式优化 添加基础样式提升用户体验:

.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button, .pagination span {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination span.active {
font-weight: bold;
color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级分页实现方案
动态页码显示 当页码较多时,可以优化显示范围:
computed: {
displayedPages() {
const range = 2 // 显示前后范围
let start = Math.max(1, this.currentPage - range)
let end = Math.min(this.totalPages, this.currentPage + range)
if (this.currentPage - range <= 1) {
end = Math.min(1 + range * 2, this.totalPages)
}
if (this.currentPage + range >= this.totalPages) {
start = Math.max(this.totalPages - range * 2, 1)
}
return Array.from({length: end - start + 1}, (_, i) => start + i)
}
}
使用分页组件 封装为可复用组件:
// Pagination.vue
<template>
<div class="pagination">
<!-- 分页结构 -->
</div>
</template>
<script>
export default {
props: {
current: { type: Number, default: 1 },
total: { type: Number, required: true },
perPage: { type: Number, default: 10 }
},
computed: {
totalPages() {
return Math.ceil(this.total / this.perPage)
}
},
methods: {
changePage(page) {
this.$emit('page-changed', page)
}
}
}
</script>
使用第三方库
考虑使用成熟的分页库如vuejs-paginate:

npm install vuejs-paginate
import Paginate from 'vuejs-paginate'
export default {
components: { Paginate },
methods: {
handlePageClick(page) {
this.currentPage = page
}
}
}
<paginate
:page-count="totalPages"
:click-handler="handlePageClick"
:prev-text="'<'"
:next-text="'>'"
:container-class="'pagination'"
:page-class="'page-item'">
</paginate>
服务端分页实现
当数据量很大时,建议采用服务端分页:
API请求参数
methods: {
fetchData(page) {
axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`)
.then(response => {
this.paginatedItems = response.data.items
this.totalItems = response.data.total
})
}
}
分页信息计算
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
}
初始化加载
created() {
this.fetchData(1)
}
通过以上方法可以实现完整的Vue分页功能,根据项目需求选择客户端或服务端分页方案。






