一、VueLazyload简介
VueLazyload是一个Vue.js的插件,它可以实现图片懒加载,即使页面上有很多图片,也不会在初次渲染时全部加载,只会在图片进入可视区域时再进行加载,这样可以减轻页面的加载时间,提升用户体验。 VueLazyload支持多种loading效果,以及滚动判断方法,可以帮助我们完美的实现图片的懒加载。
二、安装配置VueLazyload
在使用VueLazyload之前,需要先引入Vue.js和VueLazyload插件。
// 引入Vue.js
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
// 引入VueLazyload插件
<script src="//unpkg.com/vue-lazyload/vue-lazyload.js"></script>
然后,在Vue实例中使用Vue.use()
方法,将VueLazyload插件引入到Vue实例中。
Vue.use(VueLazyload)
最后,在需要进行图片懒加载的<img>
标签中使用v-lazy
指令,并将图片src
属性指向loading效果的图片。如:
<img v-lazy="imageUrl" src="loading.gif">
三、滚动判断方法
VueLazyload默认使用window
作为滚动容器,如果需要实现在某个容器中进行图片懒加载,需要使用Vue.use()
方法时加入一个对象,对象中就可以指定设定的滚动容器以及触发懒加载的事件。如下:
Vue.use(VueLazyload,{
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1,
listenEvents: [ 'scroll' ],
observer: true,
container: document.querySelector('#scrollArea')
})
其中,container
指定滚动容器,listenEvents
指定触发懒加载的事件。
四、多种loading效果
VueLazyload提供了多种loading效果,可以根据自己的需求进行选择,比如Spinner
、Fade
等。如下:
Vue.use(VueLazyload, {
loading: '/path/to/loading.gif',
error: '/path/to/error.png',
attempt: 3,
lazyComponent: true,
observer: true,
preLoad: 1.3,
dispatchEvent: true,
throttleWait: 200,
listenEvents: [ 'scroll' ],
silent: true,
scale: 1.3,
adapter: {
loaded ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init }) {},
loading (listender, Init) {},
error (listender, Init) {}
},
filter: {
webp(listener, options) {}
},
plugin: []
})
五、可滚动容器内的图片懒加载
如果需要实现一个div
内图片的懒加载,只需在该div
容器上加入一个v-lazy-container
指令,指定它是滚动容器,然后在该容器内的每个image
上添加v-lazy
指令即可。如下:
<div v-lazy-container="{ selector: 'img' }">
<img v-for="src in arr" v-lazy="src">
</div>
六、使用intersectionObserver(交叉观察器)
交叉观察器是现代浏览器中的新API,它可以监控到目标区域内元素的变化情况。我们可以在VueLazyload中将其开启,让其代替原先使用的scroll
事件。如下:
Vue.use(VueLazyload, {
observer: true,
observerOptions: {
rootMargin: '0px',
threshold: 0.1
}
})
然后,我们就可以在项目中愉快的使用VueLazyload啦!