普歌-vue实现图片懒加载方式

一.v-lazy

v-lazy是一个vue封装好的一个图片懒加载工具,具体使用方式

1.安装依赖:npm install vue-lazyload

2.在main.js中全局配置

// main.js

// 引入全局依赖
import VueLazyload from 'vue-lazyload';

// 配置懒加载属性
Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: require('图片地址'), // 报错时候的图片
  loading: require('图片地址'), //加载时候的图片
  attempt: 1
});

3.页面中使用

<template>
  <div class="about">
    <img  v-lazy="src">
  </div>
</template>

<script>
export default{
  data(){
    return{
      src:'图片链接'
    }
  }
}
</script>

 二.js手写实现

 1.使用js写一个工具

// utils/ 写一个工具

window.onload = function () {
  const imgs = document.querySelectorAll('img');

  function getTop (e) {
    return e.offsetTop;
  }

  function lazyload (imgs) {
    // 可视区高度
    const h = window.innerHeight;
    // 滚动区域高度
    const s = document.body.scrollTop || document.documentElement.scrollTop;
    for (let i = 0; i < imgs.length; i++) {
      if ((h + s) > getTop(imgs[i])) {
        (function (i) {
          setTimeout(function () {
            // 不加立即执行函数i会等于9
            // 隐形加载图片或其他资源,
            // 创建一个临时图片,这个图片在内存中不会到页面上去。实现隐形加载
            const temp = new Image();
            temp.src = imgs[i].getAttribute('data-src');// 只会请求一次
            // onload判断图片加载完毕,真是图片加载完毕,再赋值给dom节点
            temp.onload = function () {
              // 获取自定义属性data-src,用真图片替换假图片
              imgs[i].src = imgs[i].getAttribute('data-src');
            };
          }, 1000);
        })(i);
      }
    }
  }
  lazyload(imgs);
  // 滚屏函数
  window.onscroll = function () {
    lazyload(imgs);
  };
};

2.也可以把这个工具也引入main.js中

3.可以封装一个小组件,方便以后使用

<template>
  <div class="lazy">
     <img src="../../dists/loading.gif" :width="width" :height="height" :data-src="URL" alt="../../dists/error.webp">
  </div>
</template>

<script>
// import '../../utils/lazy'
export default {
  props: {
    URL: {
      typeof: String
    },
    width: {
      typeof: String,
      default: '100px'
    },
    height: {
      typeof: String,
      default: '100px'
    }
  }
};
</script>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值