vue 分页功能实现
Vue 分页功能实现
分页组件基础结构
创建一个独立的 Pagination.vue 组件,包含页码按钮、上一页/下一页导航等功能。核心模板结构如下:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in pages" :key="page">
<button
@click="goToPage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
计算属性设计
通过计算属性动态生成页码数组,并处理边界情况:
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
pages() {
const range = [];
const start = Math.max(1, this.currentPage - 2);
const end = Math.min(this.totalPages, this.currentPage + 2);
for (let i = start; i <= end; i++) {
range.push(i);
}
return range;
}
}
分页逻辑方法
实现页面跳转的核心方法:
methods: {
goToPage(page) {
if (page !== this.currentPage) {
this.$emit('page-changed', page);
}
},
prevPage() {
if (this.currentPage > 1) {
this.goToPage(this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.goToPage(this.currentPage + 1);
}
}
}
父组件集成
在父组件中绑定分页事件并处理数据分片:

<template>
<div>
<table>
<!-- 显示当前页数据 -->
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<Pagination
:total-items="data.length"
:items-per-page="10"
:current-page="currentPage"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
data: [] // 原始数据
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * 10;
const end = start + 10;
return this.data.slice(start, end);
}
},
methods: {
handlePageChange(page) {
this.currentPage = page;
}
}
}
</script>
样式优化
添加基础样式增强用户体验:
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
}
.pagination button.active {
background: #42b983;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
后端分页实现(可选)
如需对接后端API,修改分页事件处理:

methods: {
async handlePageChange(page) {
this.currentPage = page;
const res = await axios.get('/api/data', {
params: {
page,
size: 10
}
});
this.data = res.data.items;
this.totalItems = res.data.total;
}
}
高级功能扩展
-
每页条数选择器
<select v-model="itemsPerPage" @change="resetPagination"> <option value="10">10条/页</option> <option value="20">20条/页</option> </select> -
跳转到指定页码
<input type="number" :min="1" :max="totalPages" v-model="jumpPage" @keyup.enter="goToPage(jumpPage)" > -
添加省略号显示 在计算属性中处理页码范围时,可以添加
...指示符:if (start > 1) range.unshift('...'); if (end < this.totalPages) range.push('...');






