一、VueLazyload簡介
VueLazyload是一個Vue.js的插件,它可以實現圖片懶載入,即使頁面上有很多圖片,也不會在初次渲染時全部載入,只會在圖片進入可視區域時再進行載入,這樣可以減輕頁面的載入時間,提升用戶體驗。
VueLazyload支持多種loading效果,以及滾動判斷方法,可以幫助我們完美的實現圖片的懶載入。
二、安裝配置VueLazyload
在使用VueLazyload之前,需要先引入Vue.js和VueLazyload插件。
// 引入Vue.js <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> // 引入VueLazyload插件 <script src="//unpkg.com/vue-lazyload/vue-lazyload.js"></script>
然後,在Vue實例中使用Vue.use()方法,將VueLazyload插件引入到Vue實例中。
Vue.use(VueLazyload)
最後,在需要進行圖片懶載入的<img>標籤中使用v-lazy指令,並將圖片src屬性指向loading效果的圖片。如:
<img v-lazy="imageUrl" src="loading.gif">
三、滾動判斷方法
VueLazyload默認使用window作為滾動容器,如果需要實現在某個容器中進行圖片懶載入,需要使用Vue.use()方法時加入一個對象,對象中就可以指定設定的滾動容器以及觸發懶載入的事件。如下:
Vue.use(VueLazyload,{ preLoad: 1.3, error: 'dist/error.png', loading: 'dist/loading.gif', attempt: 1, listenEvents: [ 'scroll' ], observer: true, container: document.querySelector(『#scrollArea』) })
其中,container指定滾動容器,listenEvents指定觸發懶載入的事件。
四、多種loading效果
VueLazyload提供了多種loading效果,可以根據自己的需求進行選擇,比如Spinner、Fade等。如下:
Vue.use(VueLazyload, { loading: '/path/to/loading.gif', error: '/path/to/error.png', attempt: 3, lazyComponent: true, observer: true, preLoad: 1.3, dispatchEvent: true, throttleWait: 200, listenEvents: [ 'scroll' ], silent: true, scale: 1.3, adapter: { loaded ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init }) {}, loading (listender, Init) {}, error (listender, Init) {} }, filter: { webp(listener, options) {} }, plugin: [] })
五、可滾動容器內的圖片懶載入
如果需要實現一個div內圖片的懶載入,只需在該div容器上加入一個v-lazy-container指令,指定它是滾動容器,然後在該容器內的每個image上添加v-lazy指令即可。如下:
<div v-lazy-container="{ selector: 'img' }"> <img v-for="src in arr" v-lazy="src"> </div>
六、使用intersectionObserver(交叉觀察器)
交叉觀察器是現代瀏覽器中的新api,它可以監控到目標區域內元素的變化情況。我們可以在VueLazyload中將其開啟,讓其代替原先使用的scroll事件。如下:
Vue.use(VueLazyload, { observer: true, observerOptions: { rootMargin: '0px', threshold: 0.1 } })
然後,我們就可以在項目中愉快的使用VueLazyload啦!
原創文章,作者:SWOI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/146833.html