vue中实现分页
vue中实现分页的方法
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,适合快速集成。需先安装Element UI库。
安装命令:
npm install 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>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [], // 所有数据
currentPage: 1,
pageSize: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.pageSize);
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.data.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
}
</script>
结合后端API实现分页
实际项目中,通常需要从后端获取分页数据。
示例代码:
<template>
<div>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
list: []
}
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
};
axios.get('/api/data', { params })
.then(response => {
this.list = response.data.list;
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:disabled {
cursor: not-allowed;
opacity: 0.5;
}






