如何使用flexbox为Vue项目中的无序列表实现分页功能
Vue Flexbox 分页实现方案
以下是可直接复用的完整实现代码:
<template> <div id="app"> <!-- 列表区域 --> <ul class="list-container"> <li v-for="item in paginatedItems" :key="item.id" class="list-item"> <div class="item-base"> {{ item.pub_date }} {{item.image.file}} {{item.title}} </div> <div class="downloads"> <span v-for="downloadable in item.downloadable.filter(d => !!d.document_en)" :key="downloadable.id" >{{ downloadable.document_en.file }}</span> </div> </li> </ul> <!-- 分页控件 核心使用flex布局 --> <div class="pagination"> <button @click="currentPage -= 1" :disabled="currentPage === 1" class="page-btn" > 上一页 </button> <button v-for="page in totalPage" :key="page" @click="currentPage = page" class="page-btn" :class="{ active: currentPage === page }" > {{ page }} </button> <button @click="currentPage += 1" :disabled="currentPage === totalPage" class="page-btn" > 下一页 </button> </div> </div> </template> <script> export default { data() { return { // 保留你原有业务的items数据结构,可直接替换为接口返回的真实数据 items: { results: [] }, currentPage: 1, // 当前页码 pageSize: 10 // 每页展示条数,可根据需求自行调整 } }, computed: { // 切割后当前页要渲染的列表数据 paginatedItems() { const start = (this.currentPage - 1) * this.pageSize const end = start + this.pageSize return this.items.results.slice(start, end) }, // 计算总页数 totalPage() { return Math.ceil(this.items.results.length / this.pageSize) } } } </script> <style scoped> /* 列表容器flex纵向排列条目 */ .list-container { display: flex; flex-direction: column; gap: 12px; padding: 0; margin: 0; list-style: none; } /* 列表项内部flex纵向排列内容 */ .list-item { display: flex; flex-direction: column; gap: 8px; padding: 12px 0; border-bottom: 1px solid #eee; } .downloads { display: flex; flex-wrap: wrap; gap: 8px; color: #666; font-size: 14px; } /* 分页容器核心flex布局,横向居中排列按钮 */ .pagination { display: flex; justify-content: center; align-items: center; gap: 8px; margin-top: 20px; } .page-btn { padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; background: #fff; cursor: pointer; } .page-btn.active { background: #409eff; color: #fff; border-color: #409eff; } .page-btn:disabled { background: #f5f5f5; color: #ccc; cursor: not-allowed; } </style>
核心实现说明
- 数据分层处理:通过计算属性动态切割原始列表数据,仅渲染当前页对应条目,降低大列表场景的渲染压力
- 全场景flex应用:列表容器、列表项内部、附件下载区、分页导航全部使用flex布局,无需复杂浮动定位,不同设备适配性更强
- 交互边界处理:上一页/下一页按钮添加禁用状态,避免页码超出有效范围,当前页码高亮展示提升用户感知
- 自定义灵活度高:可直接修改
pageSize参数调整每页展示条数,调整flex相关属性即可快速修改排版对齐方式
内容的提问来源于stack exchange,提问作者Balazs Kelemen
相关产品推荐
相关产品推荐

