vue查询分页前端实现
Vue 分页查询前端实现
基础分页组件实现
使用 v-for 渲染分页按钮,通过 v-model 绑定当前页码:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in totalPages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: {
type: Number,
default: 10
}
},
data() {
return {
currentPage: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
changePage(page) {
this.currentPage = page
this.$emit('page-changed', page)
},
prevPage() {
if (this.currentPage > 1) this.changePage(this.currentPage - 1)
},
nextPage() {
if (this.currentPage < this.totalPages) this.changePage(this.currentPage + 1)
}
}
}
</script>
结合API请求
在父组件中处理分页数据请求:
export default {
data() {
return {
listData: [],
total: 0,
pageSize: 10
}
},
methods: {
async fetchData(page = 1) {
const res = await api.getList({
page,
size: this.pageSize
})
this.listData = res.data.list
this.total = res.data.total
}
},
mounted() {
this.fetchData()
}
}
使用Element UI分页组件
若使用Element UI,可快速实现分页:
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
性能优化建议
实现虚拟滚动应对大数据量:
import { VirtualList } from 'vue-virtual-scroll-list'
export default {
components: { VirtualList },
data() {
return {
items: [], // 所有数据
visibleData: [] // 当前页数据
}
}
}
分页样式处理
添加CSS美化分页组件:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
}
.pagination button.active {
background-color: #409eff;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
注意事项
- 分页参数应与后端约定一致(通常从1开始)
- 处理无数据时的空状态显示
- 考虑添加页面大小切换功能
- 在路由中保存当前页码实现页面刷新后保持状态







