vue項目中實現圖片懶加載的方法


對於圖片過多的頁面,為了加速頁面加載速度,所以很多時候我們需要將頁面內未出現在可視區域內的圖片先不做加載, 等到滾動到可視區域后再去加載。這樣子對於頁面加載性能上會有很大的提升,也提高了用戶體驗。

實現方法(使用vue的vue-lazyload插件)

1.安裝插件

npm install vue-lazyload --save-dev

2.在入口文件main.js中引入並使用

import VueLazyload from 'vue-lazyload'

直接使用

Vue.use(VueLazyload)

或者添加自定義選項

Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1
})

3.修改圖片顯示方式為懶加載(將 :src 屬性直接改為v-lazy)

<a href="javascript:;"><img v-lazy="'/static/img/' + item.productImage"></a>

參數選項說明

圖片懶加載的簡單效果已經實現了,然后就可以按這開發文檔的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

(想要監聽的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 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

 


至此,一個簡單的圖片懶加載就完成啦......


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM