vue前端实现分页查询
Vue 前端实现分页查询
使用 Element UI 的分页组件
安装 Element UI 库后,在组件中使用 el-pagination 实现分页功能。通过 v-model 绑定当前页码和每页条数,监听 current-change 和 size-change 事件触发数据更新。
<template>
<div>
<el-table :data="tableData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 50]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
};
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 调用API获取数据,传递 currentPage 和 pageSize 参数
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.tableData = response.data.list;
this.total = response.data.total;
});
}
},
created() {
this.fetchData();
}
};
</script>
自定义分页逻辑
如果不使用 UI 库,可以通过计算属性实现分页数据切片。定义 currentPage 和 pageSize,通过计算属性过滤当前页数据。

<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<!-- 表格内容 -->
</tr>
</table>
<div class="pagination">
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPage: 1,
pageSize: 10
};
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.pageSize);
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
axios.get('/api/data').then(response => {
this.allData = response.data;
});
}
};
</script>
<style>
.pagination button.active {
background-color: #409EFF;
color: white;
}
</style>
与后端 API 交互
分页通常需要后端支持,API 应接受 page 和 size 参数,返回分页数据及总数。前端通过 Axios 发送请求时传递这些参数。

fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.tableData = response.data.items;
this.total = response.data.totalCount;
});
}
后端响应格式示例:
{
"items": [/* 当前页数据 */],
"totalCount": 100
}
分页样式优化
通过 CSS 美化分页按钮,添加过渡效果或响应式布局。例如使用 Flexbox 居中分页控件:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
cursor: pointer;
}
性能注意事项
对于大数据量,避免一次性加载所有数据。优先采用后端分页,减少前端内存占用。若必须前端分页,可使用虚拟滚动(如 vue-virtual-scroller)优化渲染性能。






