vue分页插件实现
vue分页插件实现
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,可以直接集成到Vue项目中。安装Element UI后,在组件中引入分页组件并配置相关属性。
<template>
<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>
</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 class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
},
pages() {
const range = [];
for (let i = 1; i <= this.totalPages; i++) {
range.push(i);
}
return range;
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page);
}
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
}
.pagination button.active {
font-weight: bold;
}
</style>
使用第三方分页库
如果需要更复杂的分页功能,可以使用第三方库如vuejs-paginate。安装后,可以直接在项目中使用。
npm install vuejs-paginate
在组件中使用:

<template>
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'Prev'"
:next-text="'Next'"
:container-class="'pagination'">
</paginate>
</template>
<script>
import Paginate from 'vuejs-paginate';
export default {
components: {
Paginate
},
data() {
return {
totalPages: 10,
currentPage: 1
}
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum;
this.fetchData();
}
}
}
</script>
分页与API结合
在实际项目中,分页通常需要与后端API结合。以下是一个结合API请求的分页实现示例。
methods: {
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
.then(response => {
this.dataList = response.data.items;
this.total = response.data.total;
})
.catch(error => {
console.error(error);
});
}
}
分页样式优化
分页组件的样式可以通过CSS进一步优化,例如添加过渡效果或调整按钮间距。
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
margin: 0 5px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:hover {
background: #f0f0f0;
}
.pagination button.active {
background: #409eff;
color: #fff;
border-color: #409eff;
}






