vue怎么实现分页
Vue 实现分页的方法
使用第三方库(如 Element UI)
Element UI 提供了现成的分页组件 el-pagination,可以直接使用。安装 Element UI 后,在组件中引入分页组件并配置相关属性。
<template>
<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>
</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() {
// 根据 currentPage 和 pageSize 请求数据
}
}
};
</script>
自定义分页组件
如果需要完全自定义分页逻辑,可以手动实现分页组件。以下是一个简单的自定义分页示例。
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
}
},
data() {
return {
currentPage: 1
};
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
}
},
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);
}
}
}
};
</script>
结合后端分页
通常分页需要后端支持,前端传递页码和每页条数,后端返回对应数据。以下是一个结合 axios 请求的示例。
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.data = response.data.items;
this.total = response.data.total;
});
}
}
分页样式优化
可以根据需求调整分页样式,例如添加过渡效果或调整按钮布局。CSS 可以自由定制。

.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
通过以上方法,可以灵活实现 Vue 中的分页功能,无论是使用现成组件还是自定义逻辑都能满足需求。






