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, 50]"
: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 获取数据,传递 currentPage 和 pageSize
}
}
};
</script>
自定义分页组件
如果需要更灵活的控制,可以手动实现分页逻辑。
定义分页数据和方法:
<template>
<div>
<table>
<!-- 数据渲染 -->
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 100,
items: []
};
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
},
fetchData() {
// 根据 currentPage 和 pageSize 获取数据
}
},
created() {
this.fetchData();
}
};
</script>
分页与后端 API 交互
通常需要将分页参数传递给后端 API,例如:
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
}).then(response => {
this.items = response.data.items;
this.totalItems = response.data.total;
});
}
样式优化
为分页组件添加基础样式:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
通过以上方法,可以实现灵活的分页功能,根据项目需求选择现成组件或自定义实现。







