Vue.js 如何将全量分页组件改为带省略号的压缩显示
Vue分页组件带省略号压缩效果实现
实现思路
- 抛弃原有直接遍历全量总页数的渲染逻辑,改用响应式计算属性生成适配的压缩页码列表,列表里同时包含真实可点击的页码、标识省略号的占位符
- 设定固定的最大可见页码数,当总页数小于该值时直接展示全量页码;超过该值时自动插入省略号占位,同时始终保留第一页、最后一页的固定入口,当前页的相邻页码保持可见
- 模板渲染时对列表元素做类型判断:数字类型的元素绑定原有页码跳转逻辑、高亮样式;省略号占位渲染为不可点击的静态文本,做视觉区分
代码改造步骤
1. 新增计算属性配置
在原有组件的配置中,新增computed块,替代原有手动维护总页数、生成全量页码的逻辑:
computed: { // 自动计算总页数,替代原有手动维护的numberOfPages、getNumberOfPages方法 totalPage() { return Math.ceil(this.roles.length / this.elementsByPage) }, // 生成压缩后的分页展示列表 compressedPageList() { const total = this.totalPage const current = this.actualPage // 可根据实际横向空间调整最大可见页码数 const maxVisibleCount = 9 // 总页数小于最大可见数,直接返回全量页码,不做压缩 if (total <= maxVisibleCount) { return Array.from({ length: total }, (_, index) => index + 1) } const firstPage = 1 const lastPage = total // 当前页左右保留1个相邻页码的显示范围 const aroundRange = 1 // 当前页距离第一页较近,不显示左侧省略号 if (current <= firstPage + aroundRange + 2) { return [1, 2, 3, 4, '...', lastPage] } // 当前页距离最后一页较近,不显示右侧省略号 if (current >= lastPage - aroundRange - 2) { return [1, '...', lastPage - 3, lastPage - 2, lastPage - 1, lastPage] } // 当前页在中间位置,左右两侧都显示省略号 return [ firstPage, '...', current - 1, current, current + 1, '...', lastPage ] } }
2. 改造Pug模板结构
将原有模板中直接遍历全量页数的部分替换为遍历压缩后的页码列表,对不同类型的列表元素做差异化渲染:
ul.pagination.float-right // 保留原有上一页按钮逻辑 li.page-item a.page-link(v-on:click="prevPage()") i.icon.ion-ios-arrow-back // 遍历压缩后的分页列表 li.page-item(v-for="pageItem in compressedPageList" :key="pageItem") // 省略号占位:不可点击,静态展示 a.page-link( v-if="pageItem === '...'" @click.prevent style="cursor: default; color: #999;" ) {{ pageItem }} // 真实页码项:绑定原有跳转逻辑、当前页高亮样式 a.page-link( v-else @click="goToPage(pageItem)" :style="actualPage == pageItem && {backgroundColor: '#d3d3d3'}" ) {{ pageItem }} // 保留原有下一页按钮逻辑 li.page-item a.page-link(v-on:click="nextPage()") i.icon.ion-ios-arrow-forward
3. 调整原有方法逻辑
移除原有代码中手动维护numberOfPages、硬编码页容量的冗余部分,适配新的计算属性:
- 删除原有data配置中的
numberOfPages字段、getNumberOfPages方法,避免手动维护导致的页数不同步问题 - 调整
prevPage、nextPage方法中的总页数判断逻辑,把原有硬编码的slice截取长度替换为this.elementsByPage:
prevPage () { if (this.actualPage > 1) { this.actualPage = this.actualPage - 1 } const from = this.elementsByPage * (this.actualPage - 1) this.rolesInPage = this.roles.slice(from, from + this.elementsByPage) }, nextPage () { if (this.actualPage < this.totalPage) { this.actualPage = this.actualPage + 1 } const from = this.elementsByPage * (this.actualPage - 1) this.rolesInPage = this.roles.slice(from, from + this.elementsByPage) }, // goToPage方法原有逻辑无需改动,已兼容页码点击需求 goToPage (page) { this.actualPage = page const from = this.elementsByPage * (this.actualPage - 1) this.rolesInPage = this.roles.slice(from, from + this.elementsByPage) }
内容的提问来源于stack exchange,提问作者Fernanda Sepulveda Sura
相关产品推荐
相关产品推荐

