vue分页实现
实现Vue分页的几种方法
使用Element UI的分页组件
安装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() {
// 调用API获取数据
}
}
}
</script>
自定义分页组件
如果需要完全自定义分页,可以手动实现:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="nextPage"
: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)
}
},
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
}
}
}
</script>
结合后端API实现分页
实际项目中通常需要后端配合实现分页:
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.dataList = response.data.content
this.total = response.data.totalElements
} catch (error) {
console.error(error)
}
}
}
使用Vuex管理分页状态
在大型应用中,可以使用Vuex集中管理分页状态:
// store.js
export default new Vuex.Store({
state: {
pagination: {
currentPage: 1,
pageSize: 10,
total: 0
}
},
mutations: {
SET_PAGINATION(state, payload) {
state.pagination = payload
}
}
})
响应式分页实现
确保分页组件在窗口大小变化时也能正常显示:
.pagination {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
以上方法可以根据项目需求选择或组合使用,Element UI方案适合快速开发,自定义组件提供更大灵活性,后端API实现是生产环境的常见做法,Vuex管理适合复杂状态的应用。







