vue如何实现列表分页
实现列表分页的方法
在Vue中实现列表分页通常需要结合前端分页逻辑和后端API支持。以下是常见的实现方式:
前端分页实现
-
计算分页数据 使用
computed属性根据当前页码和每页条数切片数据:computed: { paginatedData() { const start = (this.currentPage - 1) * this.pageSize const end = start + this.pageSize return this.fullData.slice(start, end) }, totalPages() { return Math.ceil(this.fullData.length / this.pageSize) } } -
分页控件绑定 在模板中使用分页组件(如Element UI的Pagination):
<el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize" :total="fullData.length"> </el-pagination>
后端分页实现
-
API请求参数 在请求时带上分页参数:
async fetchData() { const res = await axios.get('/api/list', { params: { page: this.currentPage, size: this.pageSize } }) this.listData = res.data.items this.total = res.data.total } -
处理分页变更 监听分页组件事件重新获取数据:
methods: { handlePageChange(page) { this.currentPage = page this.fetchData() } }
常见优化技巧
- 使用
watch监听分页参数变化自动请求数据 - 添加
loading状态提升用户体验 - 对于大型数据集优先采用后端分页
- 可配置的每页显示条数选项
完整示例代码
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
listData: [],
total: 0
}
},
methods: {
async fetchData() {
const res = await api.getList({
page: this.currentPage,
size: this.pageSize
})
this.listData = res.items
this.total = res.total
}
},
created() {
this.fetchData()
}
}
以上方法可根据实际项目需求选择前端分页或后端分页方案,两者也可以结合使用。







