项目中有时候我们为了提高用户的体验,在处理图片加载的时候可能需要用到懒加载,今天就给大家介绍一款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文档的时候会发现还有其他的可配置项,这个大家就可以根据自己的需要去配置就可以了。
其他可配置项:
key | description | default | options |
---|---|---|---|
preLoad | proportion of pre-loading height(预加载高度比例) | 1.3 | Number |
error | src of the image upon load fail(图片路径错误时加载图片) | 'data-src' | String |
loading | src of the image while loading(预加载图片) | 'data-src' | String |
attempt | attempts count(尝试加载图片数量) | 3 | Number |
listenEvents | events that you want vue listen for (想要监听的vue事件) 默认['scroll']可以省略, 当插件跟页面中的动画或过渡等事件有冲突时, 可以尝试其他选项 |
| Desired Listen Events |
adapter | dynamically modify the attribute of element (动态修改元素属性) | { } | Element Adapter |
filter | the image's listener filter(动态修改图片地址路径) | { } | Image listener filter |
lazyComponent | lazyload component | false | Lazy Component |
dispatchEvent | trigger the dom event | false | Boolean |
throttleWait | throttle wait | 200 | Number |
observer | use IntersectionObserver | false | Boolean |
observerOptions | IntersectionObserver options | { rootMargin: '0px', threshold: 0.1 } | IntersectionObserver |
<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