vue实现上拉分页
Vue 实现上拉分页的方法
使用第三方库(如 better-scroll)
安装 better-scroll 库:

npm install better-scroll --save
在 Vue 组件中引入并初始化:

import BScroll from 'better-scroll'
export default {
data() {
return {
page: 1,
pageSize: 10,
list: [],
loading: false,
finished: false,
scroll: null
}
},
mounted() {
this.initScroll()
this.loadData()
},
methods: {
initScroll() {
this.scroll = new BScroll(this.$refs.wrapper, {
pullUpLoad: true,
click: true
})
this.scroll.on('pullingUp', this.loadMore)
},
loadData() {
// 模拟异步请求
setTimeout(() => {
const newData = this.getMockData(this.page, this.pageSize)
this.list = [...this.list, ...newData]
this.loading = false
this.scroll.finishPullUp()
this.scroll.refresh()
}, 500)
},
loadMore() {
if (this.finished || this.loading) return
this.loading = true
this.page++
this.loadData()
},
getMockData(page, size) {
// 模拟数据
return Array.from({length: size}, (_, i) => ({
id: (page - 1) * size + i + 1,
text: `Item ${(page - 1) * size + i + 1}`
}))
}
}
}
使用原生滚动事件监听
export default {
data() {
return {
page: 1,
pageSize: 10,
list: [],
loading: false,
finished: false
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
this.loadData()
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
if (scrollTop + windowHeight >= scrollHeight - 50 && !this.loading && !this.finished) {
this.loadMore()
}
},
loadData() {
this.loading = true
setTimeout(() => {
const newData = this.getMockData(this.page, this.pageSize)
this.list = [...this.list, ...newData]
this.loading = false
}, 500)
},
loadMore() {
this.page++
this.loadData()
}
}
}
使用 Vue 自定义指令
创建自定义指令:
Vue.directive('loadmore', {
bind(el, binding) {
const selectWrap = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
selectWrap.addEventListener('scroll', function() {
const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
if (condition) {
binding.value()
}
})
}
})
在组件中使用:
<template>
<div v-loadmore="loadMore">
<!-- 内容 -->
</div>
</template>
注意事项
- 需要处理加载状态,避免重复请求
- 列表数据为空时显示提示信息
- 滚动事件需要节流处理
- 组件销毁时需要移除事件监听
- 分页接口需要返回是否还有更多数据的标识






