一、安装
npm
npm install vue-lazyload --save-dev
CDN
CDN:
< script src = “ https://unpkg.com/vue-lazyload/vue-lazyload.js ” > < / script >
< script >
Vue 。使用( VueLazyload )
...
</ script >
二、用法
在main.js里面import这个包,而且在使用的时候可以对其进行配置
import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
// or with options
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即可。
三、配置解析
y | 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 |
四、图片的加载状态
图片的加载状态由三种:loading、loaded、error
这三种状态可以结合CSS样式来展示:
<img src="imgUrl" lazy="loading">
<img src="imgUrl" lazy="loaded">
<img src="imgUrl" lazy="error">
<style>
img[lazy=loading] {
/*your style here*/
}
img[lazy=error] {
/*your style here*/
}
img[lazy=loaded] {
/*your style here*/
}
/*
or background-image
*/
.yourclass[lazy=loading] {
/*your style here*/
}
.yourclass[lazy=error] {
/*your style here*/
}
.yourclass[lazy=loaded] {
/*your style here*/
}
</style>
五、原理