vue-lazyload具體使用細節


在vue中使用圖片懶加載詳細指南

說明

當網絡請求比較慢的時候,提前給這張圖片添加一個像素比較低的占位圖片,不至於堆疊在一塊,或顯示大片空白,讓用戶體驗更好一點。

使用方式

使用vue的 vue-lazyload 插件
插件地址:

https://www.npmjs.com/package/vue-lazyload 

案例

demo: 懶加載案例demo

Installation 安裝方式

npm


$ npm i vue-lazyload -D

CDN

CDN: https://unpkg.com/vue-lazyload/vue-lazyload.js

<script src="https://unpkg.com/vue-lazyload/vue-lazyload.js"></script> <script> Vue.use(VueLazyload) ... </script> 

用法

main.js 在入口文件


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 標簽里面的 :src 屬性 改成 v-lazy <div class="pic"> <a href="#"><img v-lazy="'/static/img/' + item.productImage" alt=""></a> </div>

參數選項說明

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

想要監聽的事件

您可以通過傳遞數組來配置想要使用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' ] })

如果您遇到這個插件重新設置加載的麻煩,這是很有用的
當你有某些動畫和過渡的時候。

轉載自:https://segmentfault.com/a/1190000011672452


免責聲明!

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



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