vue 分页 实现
Vue 分页实现方法
使用第三方库(如 Element UI)
Element UI 提供了现成的分页组件 el-pagination,适合快速集成。
安装 Element UI:
npm install element-ui
在 Vue 文件中引入并使用:
<template>
<div>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
};
},
methods: {
handleCurrentChange(val) {
this.currentPage = val;
// 加载对应页的数据
}
}
};
</script>
自定义分页组件
如果需要完全自定义分页逻辑,可以手动实现分页组件。

定义分页组件:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: Number,
totalItems: Number,
itemsPerPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
pages() {
const range = [];
for (let i = 1; i <= this.totalPages; i++) {
range.push(i);
}
return range;
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page);
}
}
}
};
</script>
<style>
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
分页数据逻辑
在父组件中处理分页数据请求或过滤:

<template>
<div>
<custom-pagination
:current-page="currentPage"
:total-items="items.length"
:items-per-page="itemsPerPage"
@page-changed="onPageChanged">
</custom-pagination>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
import CustomPagination from './CustomPagination.vue';
export default {
components: { CustomPagination },
data() {
return {
currentPage: 1,
itemsPerPage: 5,
items: [
{ id: 1, name: 'Item 1' },
// 更多数据...
]
};
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
}
},
methods: {
onPageChanged(page) {
this.currentPage = page;
}
}
};
</script>
后端分页 API 集成
如果数据来自后端 API,通常需要传递分页参数并处理返回结果。
示例 API 请求:
methods: {
fetchData(page) {
axios.get('/api/items', {
params: {
page: page,
per_page: this.itemsPerPage
}
}).then(response => {
this.items = response.data.items;
this.total = response.data.total;
});
}
}
调用时机:
onPageChanged(page) {
this.currentPage = page;
this.fetchData(page);
}
通过以上方法,可以实现 Vue 中的分页功能,无论是前端分页还是后端分页均可灵活处理。






