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() {
// 调用API获取数据,传递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: Number,
itemsPerPage: Number
},
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>
结合后端API实现分页
通常分页需要后端支持,前端传递页码和每页数量,后端返回对应数据。使用Axios调用API时,可以将分页参数作为查询条件。
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.dataList = response.data.items;
this.total = response.data.total;
});
}
}
分页样式优化
分页组件的样式可以通过CSS自定义,调整按钮、页码的布局和外观。使用Flexbox或Grid布局可以轻松实现响应式分页。

.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






