vue实现分页累加
Vue实现分页累加
基础思路
分页累加通常指滚动加载更多数据时,保留已加载内容并追加新数据。Vue中可通过监听滚动事件或结合第三方库实现。
核心代码实现
数据定义
data() {
return {
items: [], // 已加载数据
page: 1, // 当前页码
isLoading: false, // 加载状态
hasMore: true // 是否还有更多数据
}
}
加载方法

methods: {
loadMore() {
if (this.isLoading || !this.hasMore) return
this.isLoading = true
fetch(`/api/data?page=${this.page}`)
.then(res => res.json())
.then(newItems => {
this.items = [...this.items, ...newItems]
this.page++
this.hasMore = newItems.length > 0
})
.finally(() => this.isLoading = false)
}
}
滚动监听实现
模板部分
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div v-if="isLoading">加载中...</div>
</div>
滚动处理方法

handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
const bottomReached = scrollTop + clientHeight >= scrollHeight - 100
if (bottomReached) this.loadMore()
}
使用IntersectionObserver优化
观察器实现
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) this.loadMore()
})
this.$nextTick(() => {
observer.observe(this.$refs.loadingTrigger)
})
}
模板对应修改
<div v-for="item in items">{{ item.text }}</div>
<div ref="loadingTrigger" v-if="!isLoading && hasMore"></div>
<div v-if="isLoading">加载中...</div>
注意事项
- 节流处理:滚动事件建议添加节流函数
- 错误处理:网络请求需添加catch处理
- 组件销毁时移除观察者
- 移动端需考虑touch事件兼容性
完整示例组件
export default {
data() {
return {
items: [],
page: 1,
isLoading: false,
hasMore: true
}
},
methods: {
async loadMore() {
if (this.isLoading || !this.hasMore) return
this.isLoading = true
try {
const res = await fetch(`/api/data?page=${this.page}`)
const newItems = await res.json()
this.items.push(...newItems)
this.hasMore = newItems.length > 0
this.page++
} finally {
this.isLoading = false
}
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
}






