分页实现vue
分页实现(Vue)
使用Element UI的分页组件
安装Element UI库(若未安装):
npm install element-ui
在Vue项目中引入分页组件:
import { Pagination } from 'element-ui';
Vue.use(Pagination);
模板中使用分页组件:
<template>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</template>
数据与方法定义:

data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
list: []
};
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 模拟API请求
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
this.list = mockData.slice(start, end);
this.total = mockData.length;
}
}
自定义分页组件
创建自定义分页逻辑:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>第{{ currentPage }}页/共{{ totalPages }}页</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
逻辑实现:

props: {
totalItems: {
type: Number,
required: true
},
itemsPerPage: {
type: Number,
default: 10
}
},
data() {
return {
currentPage: 1
};
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.$emit('page-changed', this.currentPage);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.$emit('page-changed', this.currentPage);
}
}
}
后端API分页处理
前端请求参数:
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
后端响应结构示例:
{
"data": [],
"total": 100,
"currentPage": 1,
"pageSize": 10
}
分页样式优化
添加CSS样式增强用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 10px;
padding: 5px 15px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
color: #ccc;
cursor: not-allowed;
}






