vue中如何实现分页
实现分页的基本思路
在Vue中实现分页通常需要结合后端API和前端组件。后端负责提供分页数据,前端负责展示分页控件和处理用户交互。
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,适合快速集成:

<template>
<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>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 调用API获取数据
api.getList({
page: this.currentPage,
size: this.pageSize
}).then(response => {
this.total = response.total
this.list = response.data
})
}
}
}
</script>
自定义分页组件
如果需要自定义分页组件,可以这样实现:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
: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 range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
结合Vuex管理分页状态
在大型应用中,可以使用Vuex集中管理分页状态:

// store/modules/list.js
const state = {
pagination: {
currentPage: 1,
pageSize: 10,
total: 0
}
}
const mutations = {
SET_PAGINATION(state, payload) {
state.pagination = { ...state.pagination, ...payload }
}
}
const actions = {
async fetchList({ commit, state }) {
const { currentPage, pageSize } = state.pagination
const response = await api.getList({ page: currentPage, size: pageSize })
commit('SET_PAGINATION', { total: response.total })
return response.data
}
}
无限滚动分页
对于移动端或需要流畅体验的场景,可以实现无限滚动分页:
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollPosition = window.innerHeight + window.pageYOffset
if (scrollPosition >= document.body.offsetHeight - 200 && !this.loading) {
this.loadMore()
}
},
loadMore() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.fetchData()
}
}
}
分页性能优化
对于大数据量分页,可以考虑以下优化措施:
- 使用虚拟滚动技术只渲染可视区域内的数据
- 在后端实现游标分页而非偏移量分页
- 对分页数据进行缓存
- 实现防抖机制避免快速翻页时的多次请求
以上方法可以根据具体项目需求选择或组合使用。






