vue无限滚动实现教程
Vue 无限滚动实现方法
使用 vue-infinite-scroll 插件
安装插件:
npm install vue-infinite-scroll --save
在组件中引入并注册指令:
import infiniteScroll from 'vue-infinite-scroll'
export default {
directives: { infiniteScroll }
}
模板中使用指令:
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<!-- 内容列表 -->
</div>
实现加载方法:
data() {
return {
busy: false,
items: [],
page: 1
}
},
methods: {
loadMore() {
this.busy = true
fetch(`/api/items?page=${this.page}`)
.then(res => {
this.items.push(...res.data)
this.page++
this.busy = false
})
}
}
自定义滚动监听实现
监听滚动事件:

mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
实现滚动处理逻辑:
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const windowHeight = document.documentElement.clientHeight
const scrollHeight = document.documentElement.scrollHeight
if (scrollTop + windowHeight >= scrollHeight - 100 && !this.loading) {
this.loadMore()
}
}
}
使用 Intersection Observer API
创建观察器:
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
})
observer.observe(this.$refs.observerElement)
}
模板中添加观察元素:

<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div ref="observerElement" style="height: 1px"></div>
注意事项
确保在数据加载完成前禁用加载功能,避免重复请求
适当设置触发加载的距离阈值,提升用户体验
在组件销毁时移除事件监听,防止内存泄漏
处理网络请求错误情况,提供重试机制
考虑添加加载状态指示器,提高交互友好性






