vue实现滚动鼠标加载
Vue 实现滚动加载的方法
滚动加载(无限滚动)是常见的分页加载方式,通过监听滚动事件在用户接近底部时自动加载数据。以下是几种实现方法:

使用 IntersectionObserver API
IntersectionObserver 是现代浏览器提供的 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,
isLoading: false
}
},
mounted() {
this.initObserver();
this.loadItems();
},
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.isLoading) {
this.loadItems();
}
});
observer.observe(this.$refs.loader);
},
async loadItems() {
this.isLoading = true;
const newItems = await fetchData(this.page++);
this.items.push(...newItems);
this.isLoading = false;
}
}
}
</script>
传统滚动事件监听
适用于需要兼容旧浏览器的场景。
<template>
<div @scroll="handleScroll" style="height: 500px; overflow-y: auto;">
<!-- 内容列表 -->
</div>
</template>
<script>
export default {
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
const threshold = 100; // 距离底部阈值
if (scrollHeight - (scrollTop + clientHeight) < threshold) {
this.loadMore();
}
},
loadMore() {
// 加载数据逻辑
}
}
}
</script>
使用第三方库
vue-infinite-loading 是现成的解决方案:
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++);
this.items.push(...newItems);
$state.loaded();
if (noMoreData) $state.complete();
} catch (e) {
$state.error();
}
}
}
}
</script>
注意事项
- 添加防抖(debounce)避免频繁触发
- 在组件销毁时移除事件监听
- 处理加载状态防止重复请求
- 移动端需要考虑滚动性能优化
以上方法可根据项目需求和技术栈选择适合的方案。现代浏览器推荐优先使用 IntersectionObserver,需要兼容旧浏览器时可考虑传统滚动事件或第三方库。






