一、Lazyload简介
vue-lazyload是通过指令的方式实现的,定义的指令是v-lazy指令,指令被bind时会创建一个listener,并将其添加到listener queue里面, 并且搜索target dom节点,为其注册dom事件(如scroll事件),dom事件回调中,会遍历listener queue里的listener,判断此listener绑定的dom是否处于页面中perload的位置,如果处于则加载异步加载当前图片的资源,同时listener会在当前图片加载的过程的loading,loaded,error三种状态触发当前dom渲染的函数,分别渲染三种状态下dom的内容。

lazyload流程图
https://www.npmjs.com/package/vue-lazyload
二、Vue Lazyload插件
- 安装
npm install vue-lazyload --save-dev
- main.js引入插件
import VueLazyLoad from 'vue-lazyload'
Vue.use(VueLazyLoad,{
error:'./static/error.png',
loading:'./static/loading.png'
})
- vue文件中将需要懒加载的图片绑定 v-bind:src 修改为 v-lazy
<img class="item-pic" v-lazy="newItem.picUrl"/>
三、功能扩展
参数选项说明:
| 键 | 描述 | 默认 | 选项 |
|---|---|---|---|
| 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 forM (想要监听的vue事件) 默认['scroll']可以省略, 当插件跟页面中的动画或过渡等事件有冲突是, 可以尝试其他选项 |
['scroll'(默认),'wheel', 'mousewheel','resize', 'animationend','transitionend','touchmove'] |
Desired Listen Events |
| adapter | dynamically modify the attribute of element(动态修改元素属性) | { } | Element Adapter |
| filter | the image's listener filter(动态修改图片地址路径) | { } | Image listener filter |
| lazyComponent | 组件懒加载 | false | Lazy Component |
| dispatchEvent | 触发元素状态监听事件(error, loaded, rendered) | false | Boolean |
| throttleWait | throttle wait | 200 | Number |
| observer | use IntersectionObserver | false | Boolean |
| observerOptions | IntersectionObserver options | { rootMargin: '0px', threshold: 0.1 } | IntersectionObserver |
四、示例
import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload' //引入这个懒加载插件
Vue.use(VueLazyload)
// 或者添加VueLazyload 选项
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1
})
new Vue({
el: 'body',
components: {
App
}
})
在入口文件添加后,在组件任何地方都可以直接使用把 img 里的:src -> v-lazy:
<div class="pic">
<a href="#"><img :src="'/static/img/' + item.productImage" alt=""></a>
</div>
把之前项目中img 标签里面的 :src 属性 改成 v-lazy
<div class="pic">
<a href="#"><img v-lazy="'/static/img/' + item.productImage" alt=""></a>
</div>
可以通过传递数组来配置想要使用vue - lazyload的事件:
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1,
// the default is ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend']
listenEvents: [ 'scroll' ]
})