vue 实现分页
实现分页的基本思路
在Vue中实现分页通常需要结合后端API返回的数据和前端的分页组件。核心逻辑包括计算总页数、处理当前页码变化以及动态加载数据。
分页组件封装
使用el-pagination(Element UI)或自定义分页组件:
<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</template>
数据请求与分页参数
在Vue组件中定义分页相关数据和方法:
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
listData: []
}
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
}
axios.get('/api/data', { params }).then(res => {
this.listData = res.data.list
this.total = res.data.total
})
},
handlePageChange(val) {
this.currentPage = val
this.fetchData()
}
}
前端分页实现(纯前端)
如果数据量较小,可在前端完成分页:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.pageSize)
}
}
样式优化建议
对于自定义分页组件,可添加CSS样式:
.pagination-container {
display: flex;
justify-content: center;
margin-top: 20px;
}
.page-item {
margin: 0 5px;
cursor: pointer;
}
.active {
font-weight: bold;
}
性能优化方案
对于大数据量分页:
- 使用虚拟滚动技术(如vue-virtual-scroller)
- 实现懒加载分页(滚动到底部自动加载)
- 添加加载状态提示
- 对页码切换进行防抖处理







