vue 实现下拉加载
Vue 实现下拉加载的方法
使用 IntersectionObserver API
IntersectionObserver API 可以监听元素是否进入视口,适合实现下拉加载。
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div ref="loadMore"></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.loadData()
}
})
observer.observe(this.$refs.loadMore)
},
async loadData() {
this.isLoading = true
const newData = await fetchData(this.page)
this.list = [...this.list, ...newData]
this.page++
this.isLoading = false
}
}
}
</script>
使用 window.scroll 事件
通过监听滚动事件判断是否到达底部。

<template>
<div @scroll="handleScroll">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
page: 1,
isLoading: false
}
},
mounted() {
this.loadData()
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const windowHeight = window.innerHeight
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
if (scrollTop + windowHeight >= scrollHeight - 100 && !this.isLoading) {
this.loadData()
}
},
async loadData() {
this.isLoading = true
const newData = await fetchData(this.page)
this.list = [...this.list, ...newData]
this.page++
this.isLoading = false
}
}
}
</script>
使用第三方库
可以使用 vue-infinite-loading 等第三方库简化实现。

安装:
npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadData"></infinite-loading>
</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>
注意事项
- 添加加载状态提示避免重复请求
- 在组件销毁时移除事件监听
- 考虑数据加载完成后的处理
- 添加错误处理机制
- 对于移动端需要考虑滚动性能优化
以上方法可以根据具体需求选择适合的实现方式,IntersectionObserver API 是现代浏览器推荐的方式,而第三方库可以快速实现复杂功能。






