vue中分页怎么实现
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,适用于Vue 2项目。安装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() {
// 根据currentPage和pageSize请求数据
}
}
}
</script>
使用Ant Design Vue的分页组件
Ant Design Vue的a-pagination组件适用于Vue 3项目,功能与Element UI类似。
<template>
<a-pagination
v-model:current="currentPage"
v-model:pageSize="pageSize"
:total="total"
show-size-changer
@change="handlePageChange"
/>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const handlePageChange = () => {
// 根据currentPage和pageSize请求数据
};
return { currentPage, pageSize, total, handlePageChange };
}
}
</script>
手动实现分页逻辑
如果不依赖UI库,可以通过计算属性手动实现分页逻辑。假设有一个数据数组listData,需要按每页pageSize条数据进行分割。
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
listData: [], // 原始数据
currentPage: 1,
pageSize: 5
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.listData.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
}
</script>
结合后端API实现分页
实际项目中,分页通常需要与后端API交互。通过传递page和pageSize参数获取对应数据。
methods: {
async fetchData() {
const params = {
page: this.currentPage,
pageSize: this.pageSize
};
const res = await axios.get('/api/data', { params });
this.listData = res.data.list;
this.total = res.data.total;
}
}
分页样式自定义
如果需要自定义分页样式,可以通过覆盖UI库的CSS或手动编写样式。例如修改Element UI分页按钮颜色:
.el-pagination.is-background .el-pager li:not(.disabled).active {
background-color: #ff6b6b;
}






