vue中实现图片的懒加载

79 篇文章 0 订阅

1、安装vue-lazyload插件

npm install vue-lazyload --save-dev

2、在main.js中进行引用

import VueLazyload from "vue-lazyload";
 
Vue.use(VueLazyload);

//或者自定义配置插件
Vue.use(VueLazyload, {
preLoad: 1.3,
error: require('../src/assets/image/error.png'),
loading: require('../src/assets/image/loading.gif'),
attempt: 1
})

注意:
这里存在一个坑,当图片放在 assets文件下 的时候,要使用上面的这种 require(‘相对路径’)的写法来进行引入。当图片放在 static文件下 的时候就可以直接写路径来进行引入,像下面的写法一样。

static文件图片引入方法:

Vue.use(VueLazyload, {
preLoad: 1.3,
error: '../src/assets/image/error.png',
loading: '../src/assets/image/loading.gif',
attempt: 1
})

各个自定义配置属性含义:

keydescriptiondefaultoptions
preLoad预压高度比例1.3Number
errorsrc of the image upon load fail(指定加载失败时图片)‘data-src’String
loadingsrc of the image while loading(指定加载图片)‘data-src’String
attempt尝试计数3Number
listenEvents想要监听的事件[‘scroll’, ‘wheel’, ‘mousewheel’, ‘resize’, ‘animationend’, ‘transitionend’, ‘touchmove’]Desired Listen Events
adapter动态修改元素属性{ }Element Adapter
filter图片监听或过滤器{ }Image listener filter
lazyComponentlazyload 组件falseLazy Component
dispatchEvent触发dom事件falseBoolean
throttleWaitthrottle wait200Number
observeruse IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver options{ rootMargin: ‘0px’, threshold: 0.1 }IntersectionObserver
silentdo not print debug infotrueBoolean

3、使用(将图片设置为懒加载)

<img v-lazy="psdimg" class="psd" />

注意:
当遇到是v-for循环的时候,或者用div包裹着img的时候,需要在div上面添加 v-lazy-container=“{ selector: ‘img’ }”

<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//aaa.com/img1.jpg">
  <img data-src="//aaa.com/img2.jpg">
  <img data-src="//aaa.com/img3.jpg">  
</div>
  
<!--或者这种:-->
 
 <div v-lazy-container="{ selector: 'img' }" v-html="content">
</div>

如果是这种情况的话,一定要使用 data-src 来指定路径,而不使用v-lazy。因为如果使用的是v-lazy的话,拿到了图片地址也会一直显示不出来。

👇觉得有帮助的朋友可以支持下作者哦,您的鼓励是我创作的最大动力,如有开发问题可联系作者
请添加图片描述

  • 18
    点赞
  • 162
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值