vue3 useIntersectionObserver滚动时实现数据加载

理由:

假设一个页面很多图片,如果一下子全部加载,接口返回较慢,会阻塞页面的渲染,用户可能需要好几秒甚至更久的时间才能看到内容,这是不能忍受的

在 vue中可以使用useIntersectionObserver进行数据懒加载

@vueuse/core 提供了 useIntersectionObserver 方法

参考VueUse: useIntersectionObserver | VueUse

<template>
	<!-- 首页 -->
	<div class="mt-4">
		<SwiperBanner :swiperList="swiperList" isNavigation isShadow slideShadows :loading="swiperLoading"/>

		<div class="flex items-center py-4 titleColor">推荐</div>
		<div class="row pl-2" v-loading="listLoading" ref="loadingTarget">
			<GoodsItem v-for="(item, index) in list" :key="item.goods_id" :item="item" :index="index"/>
		</div>
	</div>
</template>

<script setup>
import { ref } from "vue";
import { useIntersectionObserver } from "@vueuse/core"

//ref引用,获取DOM
const loadingTarget = ref(null)

const listLoading = ref(false)
const list = ref([]);
const getNewGoods = async () => {
	listLoading.value = true
	const res = await newGoods();
	list.value = res;
	listLoading.value = false
};

//使用 该方法 滚动时 实现 数据懒加载
useIntersectionObserver(loadingTarget, ([{ isIntersecting }]) => {
	if(isIntersecting) {
		if(list.value.length == 0) {
			getNewGoods();
		}
	}
})

</script>

猜你喜欢

转载自blog.csdn.net/deng_zhihao692817/article/details/131536851