vue 实现前端分页
实现前端分页的基本思路
在Vue中实现前端分页,通常需要将数据存储在组件的data或computed属性中,然后通过计算当前页的数据切片进行展示。以下是具体实现方法。
定义数据和分页参数
在Vue组件的data中定义原始数据和分页相关参数:
data() {
return {
items: [], // 原始数据列表
currentPage: 1, // 当前页码
itemsPerPage: 10 // 每页显示条数
}
}
计算分页数据
使用computed属性计算当前页的数据切片:
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)
}
}
渲染分页数据
在模板中渲染分页后的数据:
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
添加分页控件
实现分页导航控件,允许用户切换页码:
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1"
>
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages"
>
下一页
</button>
</div>
样式优化
添加基础CSS样式美化分页控件:
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
margin-top: 20px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
完整组件示例
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</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 {
items: Array.from({length: 50}, (_, i) => ({id: i, name: `项目 ${i}`})),
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)
}
},
methods: {
prevPage() {
this.currentPage--
},
nextPage() {
this.currentPage++
}
}
}
</script>
<style>
/* 样式同上 */
</style>
进阶优化
对于大型数据集,可以考虑以下优化:
- 添加页码跳转输入框
- 实现页面大小选择器
- 使用Vue插件如
vue-paginate简化实现 - 添加路由支持,将当前页码反映在URL中
这种前端分页实现方式适合数据量不大的场景,如果数据量很大(如上万条),建议采用后端分页方案。







