vue-lazyload具體使用細節

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

說明

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

使用方式

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

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

案例

demo: 懶加載案例demovue

Installation 安裝方式

npm

$ npm i vue-lazyload -D

CDN

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

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

用法

main.js 在入口文件git

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的事件
監聽器的名字。github

 
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' ] })

若是您遇到這個插件從新設置加載的麻煩,這是頗有用的
當你有某些動畫和過渡的時候。npm

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

相關文章
相關標籤/搜索