vue实现页面段分页
实现分页的基本思路
在Vue中实现分页功能,通常需要以下几个关键部分:数据分片、页码控制、页面切换逻辑。分页的核心是根据当前页码和每页显示数量对数据进行切割。
数据分片处理
使用计算属性对原始数据进行分片处理,确保每次只显示当前页的数据。假设items是原始数据数组,currentPage是当前页码,itemsPerPage是每页显示数量:
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
}
}
页码控制逻辑
在模板中渲染分页按钮,并处理页码切换事件。通常需要计算总页数,并根据当前页码高亮显示对应的按钮:
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
},
methods: {
setPage(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page;
}
}
}
分页器组件示例
一个完整的分页器组件可能包含以下模板结构:
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button @click="setPage(currentPage - 1)" :disabled="currentPage === 1">
上一页
</button>
<button
v-for="page in totalPages"
:key="page"
@click="setPage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
<button @click="setPage(currentPage + 1)" :disabled="currentPage === totalPages">
下一页
</button>
</div>
</div>
</template>
分页样式优化
为分页按钮添加基础CSS样式,提升用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
动态分页参数
如果需要支持动态修改每页显示数量,可以添加选择器组件:
<select v-model="itemsPerPage">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
服务器端分页
对于大数据量场景,建议实现服务器端分页。此时需要发送页码和每页数量参数到API:
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
});
this.items = response.data.items;
this.totalCount = response.data.totalCount;
}
分页组件封装
将分页逻辑封装为可复用组件,通过props接收数据总量和当前页,通过emit事件通知父组件页码变化:
props: {
totalItems: Number,
currentPage: Number,
itemsPerPage: Number
},
emits: ['page-change'],
methods: {
changePage(page) {
this.$emit('page-change', page);
}
}






