1. 程式人生 > >element ui el-carousel 滾動圖 vue 基於vue-lazyload圖片懶載入、延遲載入 解決方案

element ui el-carousel 滾動圖 vue 基於vue-lazyload圖片懶載入、延遲載入 解決方案

vue-lazyload外掛github地址:https://github.com/hilongjw/vue-lazyload#requirements

效果是預設不載入圖片,先用一個佔位符圖來代替,等使用圖片的時再進行載入(比如滾動到圖片的時候),如果真正的圖片請求出錯了,用預設的出錯圖片來進行佔位

一、安裝外掛

$ npm install vue-lazyload --save

二、配置

//main.js
import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload, {
  preLoad: 1.3,
  attempt: 1  ,   // 載入圖片數量
   listenEvents: ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove']
})

具體配置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 ['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
silent do not print debug info true Boolean

 

三、html/js

<template>
  <el-carousel :interval="4000" indicator-position="none" id="el-carousel">
    <el-carousel-item v-for="img in list" :key="img">
      <img v-lazy="img">
    </el-carousel-item>
  </el-carousel>
</template>
  data() {
    return {
      bannerHeight: 700,
      screenWidth: 1920,
      list: [
        "http://47.107.140.8/image/home/banner1.jpg",
        "http://47.107.140.8/image/home/banner2.jpg",
        "http://47.107.140.8/image/home/banner3.jpg",
        "http://47.107.140.8/image/home/banner4.jpg"
      ]
    };
  },

四、事件監聽

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