一、vue lazyload插件:
插件地址:https://github.com/hilongjw/vue-lazyload
demo:http://hilongjw.github.io/vue-lazyload/
1.安装插件
npm install vue-lazyload -D
2.在main.js中引入并实例化配置
//实例化Vue.use(VueLazyLoad,{error:'./static/error.png',//获取错误时显示的图片loading:require('@/assets/loading.gif') //图片加载中显示的图片})//orimport Vue from 'vue'import VueLazyload from 'vue-lazyload'Vue.use(VueLazyload, {loading: require('@/assets/img/kyy_img_white.png'),preLoad: 1.5,error: require('@/assets/img/kyy_img_white.png'),attempt: 1,filter: {prefixUrl (listener, options) {console.log(listener)}}// listenEvents: [ 'scroll' ]})
如果不需要配置的话忽略上面代码,直接实例化
Vue.use(VueLazyLoad))
| key | description | default | options |
|---|---|---|---|
preLoad |
proportion of pre-loading height | 1.3 |
Number |
error |
当加载图片失败的时候 | 'data-src' |
String |
loading |
当加载图片成功的时候 | 'data-src' |
String |
attempt |
尝试计数 | 3 |
Number |
listenEvents |
想要监听的事件 | ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove'] |
Desired Listen Events |
adapter |
动态修改元素属性 | { } |
Element Adapter |
filter |
图片监听或过滤器 | { } |
Image listener filter |
lazyComponent |
lazyload component | false |
Lazy Component |
dispatchEvent |
触发dom事件 | false |
Boolean |
throttleWait |
throttle wait | 200 |
Number |
observer |
use IntersectionObserver | false |
Boolean |
observerOptions |
IntersectionObserver options | { rootMargin: ‘0px’, threshold: 0.1 } | IntersectionObserver |
3.img的src改为v-lazy
<img v-lazy="imgSrc">
4.设置样式
- tips:加载时可以不设置图片,使用背景颜色代替
//加载中的样式img[lazy=loading] {}//加载错误时的样式img[lazy=error] {}//加载后的样式img[lazy=loaded] {}
- 例子
img[lazy=loading]{transform:scaleX(0.3) scaleY(0.5);}img[lazy=loaded]{animation:appear 0.3s;animation-fill-mode: both;}@keyframes appear {from{opacity:0;}to{opacity:1;}}
二、在Vue-lazyload不生效的替补方案
手写插件
Vue.directive('imgdef', {// 当元素被插入到DOM中时...inserted () {},// 绑定,只调用1次bind (el, binding) {el.onerror = function () {el.src = require('@/assets/img/home_img_yxpp.png')}},update () {},componentUpdated () {},// 解绑时调用unbind () {}})
使用方式:v-imgdef
