vue完整实现分页
Vue 分页组件实现
分页组件模板
分页组件通常包含页码按钮、上一页/下一页按钮和跳转功能。以下是一个基础模板结构:
<template>
<div class="pagination">
<button
:disabled="currentPage === 1"
@click="changePage(currentPage - 1)"
>
上一页
</button>
<button
v-for="page in pages"
:key="page"
:class="{ active: currentPage === page }"
@click="changePage(page)"
>
{{ page }}
</button>
<button
:disabled="currentPage === totalPages"
@click="changePage(currentPage + 1)"
>
下一页
</button>
<span class="page-info">
第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
</span>
</div>
</template>
分页逻辑实现
核心分页逻辑通过计算属性和方法实现:
<script>
export default {
props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
},
maxVisiblePages: {
type: Number,
default: 5
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
const half = Math.floor(this.maxVisiblePages / 2)
let start = Math.max(this.currentPage - half, 1)
const end = Math.min(start + this.maxVisiblePages - 1, this.totalPages)
if (end - start + 1 < this.maxVisiblePages) {
start = Math.max(end - this.maxVisiblePages + 1, 1)
}
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
样式设计
基础样式确保分页组件美观可用:
<style scoped>
.pagination {
display: flex;
align-items: center;
gap: 8px;
margin-top: 20px;
}
button {
padding: 6px 12px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
border-radius: 4px;
}
button:hover:not(:disabled) {
background: #f0f0f0;
}
button.active {
background: #1890ff;
color: white;
border-color: #1890ff;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.page-info {
margin-left: 12px;
font-size: 14px;
}
</style>
父组件集成
在父组件中使用分页组件并处理数据分页:

<template>
<div>
<!-- 数据列表展示 -->
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- 分页组件 -->
<Pagination
:total-items="data.length"
:items-per-page="perPage"
:current-page="currentPage"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
data: [], // 从API获取的实际数据
perPage: 10,
currentPage: 1
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.perPage
const end = start + this.perPage
return this.data.slice(start, end)
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
// 可选: 这里可以触发API请求获取新页数据
}
},
async created() {
// 示例数据获取
this.data = await fetchData()
}
}
</script>
高级功能扩展
对于更复杂的需求,可以考虑以下扩展:
-
每页条数选择器
添加下拉菜单让用户选择每页显示数量 -
快速跳转输入框
允许用户直接输入页码跳转
-
省略号显示
当页码过多时显示省略号表示隐藏的页码 -
移动端适配
简化界面以适应小屏幕设备 -
远程分页
与后端API集成,每次翻页时请求新数据
完整实现需要根据具体项目需求调整,上述代码提供了基础分页功能的核心实现方案。






