vue2.0实现分页
vue2.0 实现分页的方法
使用 Element UI 的分页组件
Element UI 提供了现成的分页组件 el-pagination,适合快速实现分页功能。安装 Element UI 后,可以直接在模板中使用:
<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>{{ 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>
结合后端 API 实现分页
通常分页需要后端支持,通过 API 传递当前页码和每页条数:
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
}).then(response => {
this.dataList = response.data.list;
this.total = response.data.total;
});
}
}
分页样式优化
可以为分页组件添加 CSS 样式,提升用户体验:
.pagination {
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据项目需求选择使用,Element UI 的分页组件适合快速开发,自定义分页组件灵活性更高,后端 API 分页是实际项目中的常见做法。






