vue watch实现懒加载
使用 Vue 的 watch 实现懒加载
在 Vue 中,可以通过 watch 监听数据变化,结合 Intersection Observer API 或滚动事件实现懒加载。以下是具体实现方法:
监听滚动事件实现懒加载
-
定义需要懒加载的数据和状态 在组件中定义需要懒加载的数据列表和一个标志位,用于判断是否加载更多数据。
data() { return { items: [], // 已加载的数据 loading: false, // 是否正在加载 page: 1, // 当前页码 hasMore: true, // 是否还有更多数据 }; }, -
监听滚动事件 在
mounted钩子中绑定滚动事件,并在beforeDestroy中解绑。mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeDestroy() { window.removeEventListener('scroll', this.handleScroll); }, -
实现滚动处理逻辑 在
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.hasMore) { this.loadMore(); } }, async loadMore() { this.loading = true; const newItems = await fetchData(this.page); // 模拟异步请求 if (newItems.length === 0) { this.hasMore = false; } else { this.items = [...this.items, ...newItems]; this.page++; } this.loading = false; }, },
使用 Intersection Observer API 实现懒加载
-
定义观察目标和回调 使用 Intersection Observer 监听目标元素是否进入视口。
data() { return { items: [], loading: false, observer: null, }; }, mounted() { this.observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting && !this.loading) { this.loadMore(); } }); }); this.observer.observe(document.querySelector('.load-more-trigger')); }, beforeDestroy() { this.observer.disconnect(); }, -
加载更多数据 在
loadMore方法中请求数据并更新列表。methods: { async loadMore() { this.loading = true; const newItems = await fetchData(); // 模拟异步请求 this.items = [...this.items, ...newItems]; this.loading = false; }, }, -
模板中添加触发元素 在模板中放置一个触发懒加载的元素(如占位符)。
<div v-for="item in items" :key="item.id">{{ item.content }}</div> <div class="load-more-trigger" v-if="!loading"></div>
结合 watch 监听数据变化
如果需要通过 watch 监听其他数据变化触发懒加载,可以这样实现:
-
监听数据变化 使用
watch监听某个变量(如搜索关键词),变化时触发加载。watch: { searchQuery(newVal) { this.items = []; // 清空列表 this.page = 1; this.hasMore = true; this.loadMore(); }, }, -
防抖优化 避免频繁触发加载,可以使用防抖函数。
import { debounce } from 'lodash'; methods: { handleScroll: debounce(function() { // 滚动逻辑 }, 200), },
注意事项
- 懒加载需结合分页逻辑,避免一次性加载过多数据。
- 滚动事件需考虑性能问题,建议使用 Intersection Observer。
- 在组件销毁时及时解绑事件或断开观察器,避免内存泄漏。







