vue实现无限滚动加载
vue实现无限滚动加载的方法
使用Intersection Observer API
Intersection Observer API提供了一种异步观察目标元素与祖先元素或顶级文档视窗交叉状态的方法。适用于现代浏览器,性能较好。
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div ref="loader" class="loader">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1
}
},
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
})
observer.observe(this.$refs.loader)
},
methods: {
async loadMore() {
const newItems = await fetchData(this.page)
this.items = [...this.items, ...newItems]
this.page++
}
}
}
</script>
使用window滚动事件
传统方法通过监听window的scroll事件实现,需要考虑节流优化性能。

<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
isLoading: false
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
this.loadMore()
},
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.loadMore()
}
},
async loadMore() {
this.isLoading = true
const newItems = await fetchData(this.page)
this.items = [...this.items, ...newItems]
this.page++
this.isLoading = false
}
}
}
</script>
使用第三方库vue-infinite-loading
vue-infinite-loading是一个专门为Vue设计的无限滚动组件,简化了实现过程。
安装:

npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadMore"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: { InfiniteLoading },
data() {
return {
items: [],
page: 1
}
},
methods: {
async loadMore($state) {
try {
const newItems = await fetchData(this.page)
if (newItems.length) {
this.items = [...this.items, ...newItems]
this.page++
$state.loaded()
} else {
$state.complete()
}
} catch (error) {
$state.error()
}
}
}
}
</script>
性能优化建议
实现无限滚动时需要考虑性能优化,避免重复渲染和内存泄漏。
- 使用虚拟滚动技术处理大量数据
- 合理设置节流时间
- 及时清理不再需要的监听器
- 考虑使用keep-alive缓存已加载内容
- 实现错误处理和重试机制
每种方法各有优缺点,Intersection Observer API最现代化但兼容性需要考虑,传统scroll事件兼容性好但性能稍差,第三方库最便捷但增加项目依赖。根据项目需求选择合适方案。






