vue 前端实现伪分页
Vue 前端实现伪分页的方法
伪分页(前端分页)适用于数据量较小的情况,通过一次性加载所有数据后在前端进行分页展示,减少后端请求压力。以下是实现步骤:
数据准备与分页逻辑
在 Vue 的 data 中定义分页相关变量:

data() {
return {
allData: [], // 存储所有数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页显示条数
paginatedData: [] // 当前页数据
};
}
通过计算属性动态截取当前页数据:
computed: {
displayedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
}
分页控件实现
使用按钮或分页组件控制页码切换:

<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
添加分页方法:
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.pageSize);
}
}
数据加载示例
通过 mounted 或异步请求加载数据:
mounted() {
// 模拟异步数据加载
setTimeout(() => {
this.allData = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
content: `项目 ${i + 1}`
}));
}, 500);
}
完整组件示例
<template>
<div>
<ul>
<li v-for="item in displayedData" :key="item.id">{{ item.content }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [],
currentPage: 1,
pageSize: 10
};
},
computed: {
displayedData() {
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);
}
},
methods: {
prevPage() { if (this.currentPage > 1) this.currentPage--; },
nextPage() { if (this.currentPage < this.totalPages) this.currentPage++; }
},
mounted() {
this.allData = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
content: `项目 ${i + 1}`
}));
}
};
</script>
优化建议
- 性能考虑:数据量超过 1000 条时建议改用后端分页。
- UI 增强:可集成第三方分页组件如
el-pagination(Element UI)或b-pagination(Bootstrap Vue)。 - 本地存储:若需持久化分页状态,可使用
localStorage保存currentPage。
通过上述方法,无需后端接口即可实现基本分页功能,适合静态数据或小型应用场景。






