vue-lazyload插件github地址:https://github.com/hilongjw/vue-lazyload#requirements
效果是默认不加载图片,先用一个占位符图来代替,等使用图片的时再进行加载(比如滚动到图片的时候),如果真正的图片请求出错了,用默认的出错图片来进行占位
一、安装插件
$ npm install vue-lazyload --save
二、配置
//main.js
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
attempt: 1 , // 加载图片数量
listenEvents: ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']
})
具体配置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 | ['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 |
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 |
silent |
do not print debug info | true |
Boolean |
三、html/js
<template>
<el-carousel :interval="4000" indicator-position="none" id="el-carousel">
<el-carousel-item v-for="img in list" :key="img">
<img v-lazy="img">
</el-carousel-item>
</el-carousel>
</template>
data() {
return {
bannerHeight: 700,
screenWidth: 1920,
list: [
"http://47.107.140.8/image/home/banner1.jpg",
"http://47.107.140.8/image/home/banner2.jpg",
"http://47.107.140.8/image/home/banner3.jpg",
"http://47.107.140.8/image/home/banner4.jpg"
]
};
},
四、事件监听
可以通过传递数组来配置想要使用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' ]
})