使用 vue-lazyload 进行图片懒加载
一、需求
对某个大列表的图片需要进行懒加载,直接使用了 vue 的第三方插件 vue-lazyload
,(这好像是用的最多的插件,也的确很好用)
vue-lazyload
github地址:
在线demo地址:
二、基本使用
安装:
yarn add vue-lazyload
引入
import VueLazyload from 'vue-lazyload'
Vue.use
vue 在 use 的时候,存在配置项目,主要配置如下:
preLoad
: 图片加载的高度范围比例,默认为1.3,数字越大,预加载图片越多,数字越小,预加载图片数量越少error
: 加载错误的代替图片(使用 require 直接引入 src 中的图片)loading
: 加载时的 loading 图片(使用 require 直接引入 src 中的图片)attempt
: 尝试加载的次数 默认为3
const lazyloadOptions = {
preLoad: 1.3,
error: require("@/assets/images/error.png"),
loading: require("@/assets/images/loading.gif"),
attempt: 1
};
Vue.use(VueLazyload,options);
在 template 中使用
如果是写在 template 的模板代码,可以直接使用 v-lazy
指定图片地址,如:
<img v-lazy="item.imgurl" :alt="item.creator.name" width="50" height="50">
如果是在普通的 html 代码中使用,则需要指定一个 v-lazy-container
的属性,并且指定选择器是什么:
(用的比较少)
<div v-lazy-container="{ selector: 'img' }">
<img data-src="//domain.com/img1.jpg">
<img data-src="//domain.com/img2.jpg">
<img data-src="//domain.com/img3.jpg">
</div>
三、其他的一些经常用的配置项
listenEvents
:希望 vue 监听的事件,默认值:['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']
filter
:图片类型的过滤,可以做到动态的修改图片的 srclazyComponent
:是否使用懒加载组件
使用内置的懒加载组件,能够做更多额外的工作,比如:
<lazy-component @show="handler">
<img class="mini-cover" :src="img.src" width="100%" height="400">
</lazy-component>
<script>
{
...
methods: {
handler (component) {
console.log('this component is showing')
}
}
}
</script>
observer
:是否使用IntersectionObserver
这个API兼容性非常差现在,可以参考:
文章版权:Postbird-There I am , in the world more exciting!
本文链接:http://ptbird.cn/vue-lazyload-img-lazy-load.html
转载请注明文章原始出处 !
扫描二维码,在手机阅读!
好东西谢谢~~