vue page 实现分页
实现 Vue 分页功能的方法
使用 Element UI 的分页组件
安装 Element UI 后,可以直接使用 el-pagination 组件实现分页功能。
<template>
<div>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 调用 API 获取数据
console.log(`当前页: ${this.currentPage}, 每页显示: ${this.pageSize}`);
}
}
}
</script>
使用自定义分页组件
如果需要完全自定义分页组件,可以手动实现分页逻辑。

<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>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number
},
data() {
return {
currentPage: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
pages() {
const pages = [];
for (let i = 1; i <= this.totalPages; i++) {
pages.push(i);
}
return pages;
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.$emit('page-changed', this.currentPage);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.$emit('page-changed', this.currentPage);
}
},
goToPage(page) {
this.currentPage = page;
this.$emit('page-changed', this.currentPage);
}
}
}
</script>
<style>
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
结合 API 实现数据分页
通常分页需要与后端 API 配合,以下是一个结合 axios 的示例。
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.dataList = response.data.items;
this.total = response.data.total;
} catch (error) {
console.error('获取数据失败:', error);
}
}
}
使用 Vue Paginate 插件
Vue Paginate 是一个轻量级的分页插件,适合简单场景。

安装插件:
npm install vue-paginate
使用示例:
import VuePaginate from 'vue-paginate';
Vue.use(VuePaginate);
<template>
<div>
<paginate
:page-count="totalPages"
:click-handler="goToPage"
:prev-text="'Prev'"
:next-text="'Next'"
:container-class="'pagination'">
</paginate>
</div>
</template>
以上方法涵盖了从 UI 组件库到自定义实现的不同分页方案,可以根据项目需求选择合适的方式。






