Vue自定义指令实现图片懒加载效果

vue的懒加载插件很多,自己实现也不难,而且更加精简,调试起来也方便,只要理解了原理,无论是用vue还是react,都能轻松搞定

原理

当图片不在区域时,可用默认图片占位src,或者不设置src。用data属性保存图片的url地址,当图片出现在可视区域时,把src替换为data中保存的url即可

<template>
<img src="../static/images/default.jpg" :data-src="imgUrl" class="imgLazyLoad" v-lazyload>
<template>
<script>

let imgList = []
let delay
let time = 250
let offset = 0

// 节流函数,防止短时间多次触发_loadImg
function _delay () {
  clearTimeout(delay)
  delay = setTimeout(() => {
    _loadImg()
  }, time)
}

function _loadImg () {
  for (let i = 0, len = imgList.length; i < len; i++) {
    if (_isShow(imgList[i])) {
      imgList[i].src = imgList[i].getAttribute('data-src');
      imgList.splice(i, 0)
    }
  }
}

function _isShow (el) {
  // getBoundingClientRect获取图片相对视口的位置
  let coords = el.getBoundingClientRect()
  // 判断图片出否出现在可视区
  return coords.top <= document.documentElement.clientHeight + parseInt(offset)
}
export default {
  directives: {
    lazyload: {
      bind (el, binding) {
        imgList.push(el)
        // 初始化,第一次进入页面时应该显示的图片
        _delay()
        window.addEventListener('scroll', _delay, false)
      }
    }
  }
}
</script>

自己动手,丰衣足食

posted @ 2021-09-30 15:15  wmui  阅读(390)  评论(0编辑  收藏  举报