vue 实现分页功能
Vue 实现分页功能的方法
使用第三方库(如 Element UI)
Element UI 提供了现成的分页组件 el-pagination,可以快速实现分页功能。
安装 Element UI:
npm install element-ui
在 Vue 文件中引入并使用:
<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() {
// 根据 currentPage 和 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,
currentPage: Number
},
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.$emit('page-changed', this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.$emit('page-changed', this.currentPage + 1);
}
},
goToPage(page) {
this.$emit('page-changed', page);
}
}
}
</script>
<style>
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
结合后端 API 实现分页
分页通常需要与后端 API 配合,传递当前页码和每页条数。
在 Vue 组件中调用 API:
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
items: []
}
},
created() {
this.fetchData();
},
methods: {
fetchData() {
axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.items = response.data.items;
this.total = response.data.total;
});
},
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
}
}
}
</script>
分页样式优化
可以通过 CSS 美化分页组件,例如添加过渡效果或响应式布局。
示例 CSS:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:hover {
background: #f5f5f5;
}
.pagination button:disabled {
cursor: not-allowed;
opacity: 0.5;
}






