vue 实现滚动加载
Vue 实现滚动加载的方法
监听滚动事件
在Vue组件中,可以通过@scroll事件监听滚动行为。通常在mounted生命周期钩子中添加事件监听器,并在beforeDestroy中移除以避免内存泄漏。
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
// 滚动逻辑处理
}
}
计算滚动位置
通过比较文档总高度、滚动条位置和可视区域高度,判断是否滚动到底部附近。以下是一个常见的判断逻辑:

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.loadMore();
}
}
加载更多数据
当滚动到底部时触发数据加载方法。需要设置加载状态防止重复请求,并在数据加载完成后更新列表。
data() {
return {
isLoading: false,
list: [],
page: 1
}
},
methods: {
async loadMore() {
if (this.isLoading) return;
this.isLoading = true;
try {
const newData = await fetchData(this.page++);
this.list = [...this.list, ...newData];
} finally {
this.isLoading = false;
}
}
}
使用Intersection Observer API
现代浏览器支持Intersection Observer API,性能优于滚动事件监听。可以观察目标元素与视口的交叉状态。

mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
observer.observe(this.$refs.observerElement);
}
第三方库实现
对于复杂场景,可以使用现成的Vue插件如vue-infinite-loading简化开发:
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
methods: {
async infiniteHandler($state) {
try {
const newData = await fetchData();
this.list.push(...newData);
$state.loaded();
if (noMoreData) $state.complete();
} catch (error) {
$state.error();
}
}
}
}
<infinite-loading @infinite="infiniteHandler"></infinite-loading>
性能优化
对于长列表,建议使用虚拟滚动技术如vue-virtual-scroller减少DOM节点数量,提升渲染性能。
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller }
}
<RecycleScroller
class="scroller"
:items="list"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<!-- 渲染单个项目 -->
</template>
</RecycleScroller>






