Vue.js自定义截断式分页实现求助:动态生成带省略号的分页组件
Vue 动态分页组件(带省略号)
问题现状
现有Vue组件代码尝试实现分页,但当前模板遍历所有页码的方式会生成重复省略号,得到错误效果:
1 2 3 ... ... ... ... ... ...
期望实现的分页效果为以下两种之一:
- 当前页码较小时:
1 2 3 ... 10 - 当前页码在中间时:
1 ... 3 4 5 ... 10
原代码如下:
脚本部分
<script setup> import { ref } from "vue" // 页码从1开始 const pageStart = ref(1) // 建议改名为currentPage更直观 const pages = ref(10) </script>
模板部分
<template> <div> <ul v-for="number in pages" :key="number"> <li v-if="number < pageStart"> <button>{{number}}</button> </li> <li v-else-if="number > 2"> ... </li> </ul> </div> </template>
解决方案
核心思路是通过计算属性生成需要显示的页码集合,精准控制数字和省略号的显示时机,而非直接遍历所有页码。
修改后的完整代码
<script setup> import { ref, computed } from "vue" // 当前页码(原pageStart,改名更直观) const currentPage = ref(1) // 总页数 const totalPages = ref(10) // 生成需要显示的页码列表 const displayPages = computed(() => { const pages = [] const total = totalPages.value const current = currentPage.value // 始终显示第一页 pages.push(1) // 当前页码大于3时,添加前省略号 if (current > 3) { pages.push('...') } // 添加当前页码附近的连续页码(前后各1个,最多显示3个) const start = Math.max(2, current - 1) const end = Math.min(total - 1, current + 1) for (let i = start; i <= end; i++) { pages.push(i) } // 当前页码小于总页数-2时,添加后省略号 if (current < total - 2) { pages.push('...') } // 总页数大于1时,始终显示最后一页 if (total > 1) { pages.push(total) } // 去重处理,避免总页数较小时出现重复内容 return [...new Set(pages)] }) </script> <template> <div class="pagination"> <ul> <li v-for="(item, index) in displayPages" :key="index"> <button v-if="typeof item === 'number'" @click="currentPage = item" :class="{ active: currentPage === item }" > {{ item }} </button> <span v-else>{{ item }}</span> </li> </ul> </div> </template> <style scoped> .pagination ul { list-style: none; padding: 0; display: flex; gap: 8px; } .pagination button { padding: 4px 8px; cursor: pointer; border: 1px solid #eee; border-radius: 4px; } .pagination button.active { background-color: #42b983; color: white; border-color: #42b983; } </style>
效果说明
- 当
currentPage = 1时,显示:1 2 3 ... 10 - 当
currentPage = 5时,显示:1 ... 4 5 6 ... 10 - 当
currentPage = 9时,显示:1 ... 8 9 10 - 总页数≤5时,自动显示所有页码,无省略号
内容的提问来源于stack exchange,提问作者JohnSea
相关产品推荐
相关产品推荐

