前端vue实现分页
前端Vue实现分页的方法
在Vue中实现分页功能可以通过多种方式完成,以下是常见的实现方法:
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,可以快速实现分页功能:

<template>
<div>
<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>
</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 v-for="page in pages"
:key="page"
@click="goToPage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</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)
},
pages() {
const pages = []
for (let i = 1; i <= this.totalPages; i++) {
pages.push(i)
}
return pages
}
},
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
},
goToPage(page) {
this.$emit('page-changed', page)
}
}
}
</script>
<style>
.pagination {
display: flex;
gap: 5px;
}
.active {
font-weight: bold;
color: blue;
}
</style>
结合API实现数据分页
实际项目中通常需要与后端API配合实现分页:

methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
})
this.dataList = response.data.items
this.total = response.data.total
} catch (error) {
console.error(error)
}
}
}
使用Vuex管理分页状态
在大型项目中,可以使用Vuex集中管理分页状态:
// store/modules/pagination.js
const state = {
currentPage: 1,
pageSize: 10,
total: 0
}
const mutations = {
SET_PAGE(state, page) {
state.currentPage = page
},
SET_PAGE_SIZE(state, size) {
state.pageSize = size
},
SET_TOTAL(state, total) {
state.total = total
}
}
const actions = {
updatePage({ commit }, page) {
commit('SET_PAGE', page)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
实现无限滚动分页
对于移动端或需要更好用户体验的场景,可以实现无限滚动分页:
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const bottomOfWindow =
document.documentElement.scrollTop + window.innerHeight >=
document.documentElement.offsetHeight - 100
if (bottomOfWindow && !this.loading && this.hasMore) {
this.currentPage++
this.fetchData()
}
}
}
以上方法可以根据项目需求选择使用或组合使用,实现适合项目的分页功能。






