VUE3 实现一个简单的图片懒加载

239 阅读1分钟

昨天晚上刷到了一条关于 vue2的vueLazyLoad 的代码解析,那个代码比较复杂,使用的 scroll来判断,我准备使用 IntersectionObserver来进行滚动监听

  <ul>
      <li v-for="(img, index) in imgArrs"  :Key="index">
        <img alt="图片" 
        v-lazyLoad="img"
        src="https://ts1.cn.mm.bing.net/th/id/R-C.289c5bdbdd838d59245fc60620532fe5?rik=pQZoPRPeXTjCHg&riu=http%3a%2f%2fimg.zcool.cn%2fcommunity%2f01c30c571a507e32f875a3997c03db.gif&ehk=8%2bGl4aOtyDN7LK26jneUOroHcjOxuIqPysGAv0ZZUg4%3d&risl=&pid=ImgRaw&r=0"
         style="height: 300px;">
      </li>
    </ul>

使用模拟图片

// pics
[
  "https://ts1.cn.mm.bing.net/th/id/R-C.901f8ebdab22d065baefeae6c2701cc0?rik=Z3Hew18zFaF%2bLQ&riu=http%3a%2f%2fwww.pp3.cn%2fuploads%2f20120418lw%2f13.jpg&ehk=Es5ZGH90h%2foCghvlIwdKfUiqpO05gLSgOEBU2i0Mwok%3d&risl=&pid=ImgRaw&r=0",
  "https://pic3.zhimg.com/v2-58d652598269710fa67ec8d1c88d8f03_r.jpg?source=1940ef5c",
  "https://www.keaidian.com/uploads/allimg/190424/24110307_8.jpg",
  "https://tse1-mm.cn.bing.net/th/id/OIP-C.QPH1IBosDYBqaU3O6wV3YAHaEo?pid=ImgDet&rs=1",
  "https://uploadfile.huiyi8.com/2013/0816/20130816031331766.jpg",
  "https://pic.qqtn.com/up/2017-7/2017071317523053609.jpg"
]

主要代码实现

const vLazyLoad = function (el: HTMLImageElement, bindings) {
  let ob = new IntersectionObserver(function (entries, observe) {
    if (entries[0].intersectionRatio > 0) {
      el.src = bindings.value;
      observe.unobserve(el)
    };
  }, {
    rootMargin: '0px 0px 350px 0px'
  })
  ob.observe(el)
}

特别说一下这个 rootMargin,我看了半天 mdn上的描述,也没有看懂 自己尝试写了一下,是类似于 margin 的东西,如果是 0的话,就是刚好进入视野触发 如果是正数,就会提前触发,和 margin 的属性一样,上右下左