vue前端实现伪分页
实现伪分页的基本思路
伪分页(前端分页)是指一次性加载所有数据,通过前端逻辑控制每页显示的数据量,无需频繁请求后端。适用于数据量较小且变动不频繁的场景。
核心代码实现
1. 数据准备与分页参数
data() {
return {
allData: [], // 全部数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
total: 0 // 总数据量
}
}
2. 计算当前页数据
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
}
}
3. 分页器逻辑
methods: {
handlePageChange(page) {
this.currentPage = page
},
handleSizeChange(size) {
this.pageSize = size
this.currentPage = 1 // 重置页码
}
}
完整组件示例
<template>
<div>
<!-- 数据展示 -->
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- 分页控件 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="handlePageChange"
:current-page="currentPage"
:page-sizes="[5, 10, 20, 50]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
allData: Array.from({length: 100}, (_, i) => ({ id: i, name: `Item ${i}` })),
currentPage: 1,
pageSize: 10,
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
total() {
return this.allData.length
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
},
handleSizeChange(size) {
this.pageSize = size
this.currentPage = 1
}
}
}
</script>
性能优化建议
对于大数据量(超过1000条),建议采用虚拟滚动技术替代传统分页,例如使用vue-virtual-scroller库。
// 安装后使用示例
import { RecycleScroller } from 'vue-virtual-scroller'
export default {
components: { RecycleScroller }
}
注意事项
- 内存消耗:所有数据保存在内存中,数据量过大会影响性能
- 数据更新:需要手动刷新数据时,应重置分页参数
- 排序/筛选:需在分页前处理完整数据集







