const{stop}=useIntersectionObserver(target,fn,options)1.参数1target表示要监听的DOM元素2.参数2是回调函数,通知监听动作(回调函数的第一个参数是Intersecting表示被监控的元素已经进入可见区域)3.第三个参数表示配置选项stop是停止观察是否进入或移出可见区域const{stop}=useIntersectionObserver(target为观察的目标dom容器,必须是dom容器,是vue3.0绑定的dom对象target,//isIntersecting进入可见区域,true进入false,移出//observerElement观察dom([{isIntersecting}],observerElement)=>{//这里可以根据isIntersecting判断,然后做业务},)业务功能场景基于此方法实现组件的懒加载第一步:在src下封装一个hook函数,在src/hooks/index.js文件夹;代码如下://封装一个通用方法实现数据的延迟加载import{useIntersectionObserver}from'@vueuse/core'import{ref}from'vue'exportconstuseLazyData=(apiFn)=>{//target代表组件最外层的div元素consttarget=ref(null)//懒加载接口返回的数据constresult=ref([])//监听组件是否进入可见areaconst{stop}=useIntersectionObserver(target,([{isIntersecting}])=>{//如果target对应的DOM进入可见区域,就会触发回调函数if(isIntersecting){//被监控的DOM有进入可视区:此时调用接口获取数据;stop继续听stop()apiFn().then(data=>{result.value=data.result})}})//result表示接口懒加载得到的业务数据//target表示监控的DOM元素,需要通过ref属性绑定templatereturn{result,target}}第二步:在需要的文件夹中导入例如:延迟加载的好处:页面加载速度快,可以减轻服务器压力,节省流量,用户体验好
