一、Lazyload簡介
vue-lazyload是通過指令的方式實(shí)現(xiàn)的,定義的指令是v-lazy指令,指令被bind時會創(chuàng)建一個listener魁巩,并將其添加到listener queue里面, 并且搜索target dom節(jié)點(diǎn)姐浮,為其注冊dom事件(如scroll事件)谷遂,dom事件回調(diào)中,會遍歷listener queue里的listener卖鲤,判斷此listener綁定的dom是否處于頁面中perload的位置肾扰,如果處于則加載異步加載當(dāng)前圖片的資源,同時listener會在當(dāng)前圖片加載的過程的loading蛋逾,loaded集晚,error三種狀態(tài)觸發(fā)當(dāng)前dom渲染的函數(shù),分別渲染三種狀態(tài)下dom的內(nèi)容区匣。
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"/>
三、功能擴(kuò)展
參數(shù)選項說明:
鍵 | 描述 | 默認(rèn) | 選項 |
---|---|---|---|
preLoad | proportion of pre-loading height(預(yù)加載高度比例) | 1.3 | Number |
error | src of the image upon load fail(圖片路徑錯誤時加載圖片) | 'data-src' | String |
loading | src of the image while loading(預(yù)加載圖片) | 'data-src' | String |
attempt | attempts count(嘗試加載圖片數(shù)量) | 3 | Number |
listenEvents | events that you want vue listen forM (想要監(jiān)聽的vue事件) 默認(rèn)['scroll']可以省略亏钩, 當(dāng)插件跟頁面中的動畫或過渡等事件有沖突是莲绰, 可以嘗試其他選項 |
['scroll'(默認(rèn)),'wheel', 'mousewheel','resize', 'animationend','transitionend','touchmove'] |
Desired Listen Events |
adapter | dynamically modify the attribute of element(動態(tài)修改元素屬性) | { } | Element Adapter |
filter | the image's listener filter(動態(tài)修改圖片地址路徑) | { } | Image listener filter |
lazyComponent | 組件懶加載 | false | Lazy Component |
dispatchEvent | 觸發(fā)元素狀態(tài)監(jiān)聽事件(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 標(biāo)簽里面的 :src 屬性 改成 v-lazy
<div class="pic">
<a href="#"><img v-lazy="'/static/img/' + item.productImage" alt=""></a>
</div>
可以通過傳遞數(shù)組來配置想要使用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' ]
})