vue分页组件的实现
Vue分页组件的实现
基本结构设计
分页组件通常需要接收总数据量(total)、每页显示数量(pageSize)、当前页码(currentPage)等props。组件内部通过计算属性生成页码列表,并触发页码变更事件。
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage <= 1"
>上一页</button>
<span
v-for="page in pageList"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage >= totalPage"
>下一页</button>
</div>
</template>
核心逻辑实现
通过计算属性动态生成页码列表,处理边界情况。使用v-model实现双向绑定更便捷。

export default {
props: {
total: Number,
pageSize: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
}
},
computed: {
totalPage() {
return Math.ceil(this.total / this.pageSize)
},
pageList() {
const range = 2 // 显示前后页码数
const list = []
for (let i = this.currentPage - range; i <= this.currentPage + range; i++) {
if (i > 0 && i <= this.totalPage) {
list.push(i)
}
}
return list
}
},
methods: {
changePage(page) {
if (page < 1 || page > this.totalPage) return
this.$emit('update:currentPage', page)
this.$emit('page-change', page)
}
}
}
样式优化
添加基础样式增强交互体验,使用CSS变量方便主题定制。

.pagination {
display: flex;
gap: 8px;
}
.pagination button {
padding: 6px 12px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination span {
padding: 6px 12px;
border: 1px solid #ddd;
cursor: pointer;
}
.pagination span.active {
background: var(--primary-color, #1890ff);
color: white;
border-color: transparent;
}
高级功能扩展
支持显示总数、快速跳转、每页条数切换等功能时,可增加对应模板和逻辑。
<div class="pagination-extra">
<span>共 {{ total }} 条</span>
<select v-model="innerPageSize" @change="handleSizeChange">
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
<input
type="number"
v-model.number="inputPage"
@keyup.enter="jumpPage"
>
</div>
data() {
return {
inputPage: null,
innerPageSize: this.pageSize
}
},
methods: {
handleSizeChange() {
this.$emit('update:pageSize', this.innerPageSize)
this.$emit('size-change', this.innerPageSize)
},
jumpPage() {
if (!this.inputPage) return
this.changePage(Math.min(Math.max(1, this.inputPage), this.totalPage))
}
}
使用示例
在父组件中引入并配置分页组件,通过事件监听实现数据加载。
<pagination
:total="100"
:page-size="10"
:current-page.sync="currentPage"
@page-change="loadData"
/>
data() {
return {
currentPage: 1,
listData: []
}
},
methods: {
async loadData(page) {
const res = await api.getList({
page,
size: 10
})
this.listData = res.data
}
}






