vue实现滑动加载
实现滑动加载的基本原理
滑动加载(Infinite Scroll)的核心逻辑是监听滚动事件,当用户滚动到接近页面底部时触发数据加载。Vue中可以通过结合v-for指令和计算属性动态渲染数据,同时利用window.addEventListener或第三方库实现滚动监听。
使用原生滚动事件监听
在Vue组件的mounted钩子中添加滚动事件监听,通过计算滚动位置判断是否触发加载:
export default {
data() {
return {
items: [], // 已加载的数据列表
isLoading: false, // 是否正在加载
currentPage: 1, // 当前页码
};
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop;
const windowHeight = window.innerHeight;
const scrollHeight = document.documentElement.scrollHeight;
// 距离底部200px时触发加载
if (scrollTop + windowHeight >= scrollHeight - 200 && !this.isLoading) {
this.loadMore();
}
},
async loadMore() {
this.isLoading = true;
try {
const newItems = await fetchData(this.currentPage + 1); // 模拟API请求
this.items = [...this.items, ...newItems];
this.currentPage++;
} finally {
this.isLoading = false;
}
}
}
}
使用Intersection Observer API
更高效的现代浏览器API方案,避免频繁触发滚动事件:

export default {
data() {
return {
items: [],
observer: null,
sentinel: null,
};
},
mounted() {
this.sentinel = document.querySelector('#sentinel');
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
this.observer.observe(this.sentinel);
},
beforeDestroy() {
this.observer.disconnect();
}
}
模板中需添加哨兵元素:
<div v-for="item in items">{{ item.content }}</div>
<div id="sentinel" style="height: 1px;"></div>
使用第三方库vue-infinite-loading
对于快速实现,可以安装专用库:

npm install vue-infinite-loading
组件实现示例:
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
methods: {
async loadMore($state) {
try {
const newItems = await fetchData();
if (newItems.length) {
this.items.push(...newItems);
$state.loaded();
} else {
$state.complete();
}
} catch (error) {
$state.error();
}
}
}
}
模板结构:
<infinite-loading @infinite="loadMore">
<div slot="no-more">没有更多数据了</div>
</infinite-loading>
性能优化建议
- 添加防抖处理避免频繁触发
- 使用虚拟滚动(如vue-virtual-scroller)处理大量数据
- 服务端返回分页数据时带上总量标识
- 在移动端考虑使用下拉刷新交互
- 错误处理需包含重试机制
注意事项
- 滚动容器非window时需要调整监听目标
- 动态内容高度变化可能导致计算误差
- 骨架屏提升加载体验
- 保持加载状态可见性
- 禁用加载期间重复触发






