vue中实现分页
vue中实现分页的方法
使用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>
<div v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</div>
<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 {
data: [], // 原始数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.itemsPerPage);
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.data.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
}
</script>
结合后端API实现分页
实际项目中,分页通常与后端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.getList();
},
methods: {
getList() {
axios.get('/api/list', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(res => {
this.list = res.data.list;
this.total = res.data.total;
});
},
handlePageChange(page) {
this.currentPage = page;
this.getList();
}
}
}
</script>
使用第三方库vue-awesome-paginate
如果需要更多功能,可以使用专门的分页库如vue-awesome-paginate。安装后引入并使用。

<template>
<div>
<vue-awesome-paginate
:total-items="total"
:items-per-page="perPage"
:max-pages-shown="5"
v-model="currentPage"
:on-click="onClickHandler"
/>
</div>
</template>
<script>
import { VueAwesomePaginate } from 'vue-awesome-paginate';
export default {
components: {
VueAwesomePaginate
},
data() {
return {
currentPage: 1,
perPage: 10,
total: 100
}
},
methods: {
onClickHandler(page) {
this.currentPage = page;
this.fetchData();
}
}
}
</script>
以上方法可以根据项目需求选择适合的分页实现方式。






