通过 IntersectionObserver 一步步实现移动端懒加载

411 阅读1分钟
theme: cyanosis

前言

在vue2版本,已经替大家在公司项目测试过了。h5、微信小程序、安卓、苹果app都已跑通。nvue 有部分差异 后面有说明。

1、创建 IntersectionObserver 对象实例

微信端差异参考:developers.weixin.qq.com/miniprogram…

   // #ifdef MP-WEIXIN
  
  // vue2可以直接用this
  import { getCurrentInstance } from "vue";
  const { proxy }: any = getCurrentInstance();
 ​
  observer.value = proxy.createIntersectionObserver({
   // options 
  })
  // #endif
  // #ifndef MP-WEIXIN
  observer.value = uni.createIntersectionObserver(this,{
   // options 
  })
  // #endif
  
 ​

2、指定参照区域

  
  observer.value.relativeToViewport({
    // options 
  })

3、指定目标节点并开始监听相交状态变化情况

  observer.value.observe("#" + snowflakeID, (res: any) => {
    if (res.intersectionRatio > 0) {
      show.value = true
    }
  });

4、销毁

  // 显示后调用后、组件销毁前 需要销毁监听器
  observer.value.disconnect();

5、nvue补充

nvue限制介绍:uniapp.dcloud.net.cn/tutorial/nv…

因为nvue没有IntersectionObserver 对象,用appear api代替

详情看api介绍:uniapp.dcloud.net.cn/tutorial/nv…

  <template>
      <view @appear="nVueLazyLoad"> </view>
  </template>
  <script setup lang="ts">
  const nVueLazyLoad = () => {
      if (show.value)  return;
      show.value = true
  };
  </script>

使用该是有弊端的,在非滚动区域无法触发!!!所以使用时需要注意。

6、实现更完善的组件封装

简单封装一个懒加载容器组件

文章介绍:juejin.cn/post/745714…

源码:github.com/1611037570/…

详情封装一个图片加载组件

文章介绍:juejin.cn/post/745612…

源码:github.com/1611037570/…