vue实现列表懒加载
实现列表懒加载的方法
使用 Intersection Observer API
Intersection Observer API 可以监听元素是否进入视口,适合实现懒加载。在 Vue 中可以通过自定义指令或组件实现。
// 自定义指令
Vue.directive('lazy-load', {
inserted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
binding.value();
observer.unobserve(el);
}
});
});
observer.observe(el);
}
});
// 模板中使用
<div v-lazy-load="loadMore">加载更多...</div>
使用滚动事件监听
通过监听滚动事件,计算滚动位置和元素高度,触发加载更多数据。
methods: {
handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const windowHeight = window.innerHeight;
const documentHeight = document.body.scrollHeight;
if (scrollTop + windowHeight >= documentHeight - 100) {
this.loadMore();
}
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
使用第三方库
Vue 生态中有一些现成的懒加载库,如 vue-lazyload 或 vue-infinite-loading,可以快速实现功能。
// 安装 vue-infinite-loading
npm install vue-infinite-loading
// 在组件中使用
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.text }}</div>
<infinite-loading @infinite="loadMore"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
methods: {
loadMore($state) {
// 加载数据逻辑
$state.loaded();
// 如果没有更多数据
$state.complete();
}
}
};
</script>
虚拟滚动优化
对于超长列表,可以使用虚拟滚动技术(如 vue-virtual-scroller)减少 DOM 数量,提升性能。
// 安装 vue-virtual-scroller
npm install vue-virtual-scroller
// 在组件中使用
<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div>{{ item.text }}</div>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller }
};
</script>
注意事项
- 懒加载需要合理设置触发阈值,避免频繁触发。
- 使用 Intersection Observer 时注意兼容性,必要时添加 polyfill。
- 虚拟滚动适用于固定高度的列表项,动态高度需要额外处理。
以上方法可以根据实际需求选择或组合使用,以达到最佳性能和用户体验。







