vue实现分页技术
Vue实现分页技术
基础分页实现
使用v-for和计算属性实现基础分页。定义一个currentPage变量和itemsPerPage常量,通过计算属性paginatedItems返回当前页的数据:
data() {
return {
items: [], // 数据源
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
}
模板部分渲染分页数据和控制按钮:
<ul>
<li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="currentPage++" :disabled="currentPage >= totalPages">下一页</button>
分页组件封装
创建可复用的分页组件Pagination.vue:
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: Number
},
emits: ['page-change'],
methods: {
changePage(page) {
this.$emit('page-change', page);
}
}
模板实现页码导航:
<div class="pagination">
<button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
<template v-for="page in totalPages" :key="page">
<button
@click="changePage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
</template>
<button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>
</div>
服务器端分页
对于大数据量场景,建议实现服务器端分页。通过API接口传递分页参数:
methods: {
async fetchData(page = 1) {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
});
this.items = response.data.items;
this.totalItems = response.data.total;
}
}
分页样式优化
添加CSS样式增强用户体验,例如当前页高亮、禁用状态等:
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级功能扩展
实现更复杂的分页功能:
- 添加页面大小选择器
- 实现页码跳转输入框
- 添加总条目数显示
- 实现省略号处理大量页码
data() {
return {
pageSizeOptions: [10, 20, 50, 100]
}
},
methods: {
handlePageSizeChange(size) {
this.itemsPerPage = size;
this.currentPage = 1;
this.fetchData();
}
}
以上方案可根据实际项目需求组合使用,基础分页适合客户端少量数据,服务器端分页适合大数据量场景,组件化封装提高代码复用性。







