vue实现上拉加载
Vue 实现上拉加载的方法
使用 Intersection Observer API
Intersection Observer API 提供了一种异步观察目标元素与祖先元素或顶级文档视窗交叉状态的方法。适合实现上拉加载。
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div ref="loadMore" class="load-more"></div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
page: 1,
isLoading: false
}
},
mounted() {
this.initObserver()
this.loadData()
},
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.isLoading) {
this.page++
this.loadData()
}
})
observer.observe(this.$refs.loadMore)
},
async loadData() {
this.isLoading = true
try {
const newData = await fetchData(this.page)
this.list = [...this.list, ...newData]
} finally {
this.isLoading = false
}
}
}
}
</script>
<style>
.load-more {
height: 20px;
}
</style>
使用滚动事件监听
传统方法通过监听滚动事件判断是否到达底部。

<template>
<div ref="container" @scroll="handleScroll">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div v-if="isLoading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
page: 1,
isLoading: false
}
},
mounted() {
this.loadData()
},
methods: {
handleScroll() {
const container = this.$refs.container
const scrollHeight = container.scrollHeight
const scrollTop = container.scrollTop
const clientHeight = container.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 10 && !this.isLoading) {
this.page++
this.loadData()
}
},
async loadData() {
this.isLoading = true
try {
const newData = await fetchData(this.page)
this.list = [...this.list, ...newData]
} finally {
this.isLoading = false
}
}
}
}
</script>
使用第三方库
可以使用现成的 Vue 插件如 vue-infinite-loading 简化实现。

安装:
npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<InfiniteLoading @infinite="loadData" />
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: { InfiniteLoading },
data() {
return {
list: [],
page: 1
}
},
methods: {
async loadData($state) {
try {
const newData = await fetchData(this.page)
if (newData.length) {
this.list = [...this.list, ...newData]
this.page++
$state.loaded()
} else {
$state.complete()
}
} catch (error) {
$state.error()
}
}
}
}
</script>
性能优化建议
- 节流处理滚动事件,避免频繁触发
- 添加加载状态提示,提升用户体验
- 在组件销毁时移除事件监听
- 考虑使用虚拟滚动处理大量数据
以上方法可根据具体需求选择实现,Intersection Observer API 是现代浏览器推荐的方式,而第三方库可以快速实现完整功能。






