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() {
// 调用API获取数据
}
}
}
</script>
自定义分页组件
如果需要更灵活的控制,可以手动实现分页逻辑。
模板部分:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
脚本部分:
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
allItems: [] // 从API获取的所有数据
}
},
computed: {
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage);
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.allItems.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
},
async created() {
// 获取数据
this.allItems = await fetchData();
}
}
</script>
结合API实现后端分页
对于大数据量,建议使用后端分页。
API调用示例:
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.items = response.data.items;
this.total = response.data.total;
}
分页控制部分与前面示例类似,主要区别在于数据获取方式。
样式优化
可以为分页组件添加基础样式:

.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
以上方法涵盖了从UI库集成到自定义实现的不同方案,可根据项目需求选择合适的方式。





