Vue项目中图片懒加载

项目中有时候我们为了提高用户的体验,在处理图片加载的时候可能需要用到懒加载,今天就给大家介绍一款vue项目中比较方便好用的图片懒加载的插件:vue-lazyload。
1.安装插件

npm install vue-lazyload --save-dev

2.在入口文件main.js中引入并使用

import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload)

这里呢我们也可以添加自定义选项,例如加载错误,正在加载时的图片等

Vue.use(VueLazyLoad,{
    preLoad: 1.3,
    error: './static/error.png',
    loading: './static/loading.gif',
    attempt: 1
})

3.接下来就是使用了,使用的时候,把原来图片显示方式修改为懒加载(即将 :src 属性改为v-lazy)

<img v-lazy="newItem.picUrl"/>

如果是循环的话

<img v-for="imgItem in imgList" v-lazy="imgItem">

这就简单的完成了vue项目中图片懒加载的效果了。
我们在看官方API文档的时候会发现还有其他的可配置项,这个大家就可以根据自己的需要去配置就可以了。

其他可配置项:

keydescriptiondefaultoptions
preLoadproportion of pre-loading height(预加载高度比例)1.3Number
errorsrc of the image upon load fail(图片路径错误时加载图片)'data-src'String
loadingsrc of the image while loading(预加载图片)'data-src'String
attemptattempts count(尝试加载图片数量)3Number
listenEvents

events that you want vue listen for

(想要监听的vue事件)

默认['scroll']可以省略,

当插件跟页面中的动画或过渡等事件有冲突时,

可以尝试其他选项

['scroll'(默认),

'wheel',

'mousewheel',

'resize',

'animationend',

'transitionend',

'touchmove']

Desired Listen Events
adapter

dynamically modify the attribute of element

(动态修改元素属性)

{ }Element Adapter
filterthe image's listener filter(动态修改图片地址路径){ }Image listener filter
lazyComponentlazyload componentfalseLazy Component
dispatchEventtrigger the dom eventfalseBoolean
throttleWaitthrottle wait200Number
observeruse IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver options{ rootMargin: '0px', threshold: 0.1 }IntersectionObserver

另外。除了上面我们所说的通过改变src 属性的加载方式外我们也可以通过设置css 来实现加载状态
<img src="imgUrl" lazy="loading">
<img src="imgUrl" lazy="loaded">
<img src="imgUrl" lazy="error">

这个时候我们就需要使用选择器,来给每一个状态添加相应的样式

<style>
  img[lazy=loading] {
    /*你自己的样式*/
  }
  img[lazy=error] {
    /*你自己的样式*/
  }
  img[lazy=loaded] {
    /*你自己的样式*/
  }
</style>

这个时候我们会发现,如果我们不想使用图片的话而是想使用颜色的话,就可以在自己样式里面来写我们自己想要的颜色了。

OK,其他的可配置项具体的使用和例子可以去官网看一下:https://github.com/hilongjw/vue-lazyload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值