当前位置: 首页 > 工具软件 > Lazy Load > 使用案例 >

Vue-Lazyload学习文档

司马耘豪
2023-12-01

Vue-Lazyload懒加载

注:此文档中的配置实例中文文档为机翻和根据自我理解进行的翻译
可能如原文有出入,若想理解原意请看英语文档

原官方文档地址:https://www.npmjs.com/package/vue-lazyload

1、安装

npm i vue-lazyload -S

2、使用

2.1、main.js导入并配置


import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload, {
 preLoad: 1.3,
 error: 'dist/error.png',		//img的加载中的显示的图片的路径
 loading: 'dist/loading.gif',	//img加载失败时现实的图片的路径
 attempt: 1,					//尝试加载的次数
 listenEvents['scroll','wheel','mousewheel','resize','animationend','	transitionend','touchmove'],  //你想让vue监听的事件
})

new Vue({
 el: 'app',
 components: {
   App
 }
})
<ul>
 <li v-for="img in list" >
   <img v-lazy="img.src" >
 </li>
</ul>

use v-lazy-container work with raw HTML

使用v-lazy-container与原始的HTML工作

<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//domain.com/img1.jpg">
  <img data-src="//domain.com/img2.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>

custom error and loading placeholder image

自定义errorloading占位符图像

<div v-lazy-container="{ selector: 'img', error: 'xxx.jpg', loading: 'xxx.jpg' }">
  <img data-src="//domain.com/img1.jpg">
  <img data-src="//domain.com/img2.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>
<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//domain.com/img1.jpg" data-error="xxx.jpg">
  <img data-src="//domain.com/img2.jpg" data-loading="xxx.jpg">
  <img data-src="//domain.com/img3.jpg">  
</div>

3、配置选项

属性描述默认值选项
preLoad预载高度比例1.3Number
errorimg的加载失败显示的图片的路径‘data-src’String
loadingimg的加载中的显示的图片的路径‘data-src’String
attempt尝试次数3Number
listenEvents您想要Vue监听的事件[‘scroll’, ‘wheel’, ‘mousewheel’, ‘resize’, ‘animationend’, ‘transitionend’, ‘touchmove’]监听的事件(Desired Listen Events)
adapter动态修改element的属性{}属性对象(Element Adapter)
filter图像的侦听器过滤器{}图像侦听器/过滤器(Image listener filter)
lazyComponent延迟加载组件false懒加载组件(Lazy Component)
dispatchEvent触发dom事件falseBoolean
throttleWait200Number
observer使用IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver选项{ rootMargin: ‘0px’, threshold: 0.1 }交叉观察者(IntersectionObserver)
silent不打印调试信息trueBoolean

4、具体配置示例

4.1、listenEvents

You can configure which events you want vue-lazyload by passing in an array of listener names.

您可以通过传入侦听器名称数组来配置需要vue-lazyload的事件。

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'dist/error.png',
  loading: 'dist/loading.gif',
  attempt: 1,
  //默认值为 ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend']
  listenEvents: [ 'scroll' ]
})

This is useful if you are having trouble with this plugin resetting itself to loading when you have certain animations and transitions taking place

如果您在发生某些动画和转换时,在此插件重置为加载时遇到问题,这是很有用的

4.2、 filter

dynamically modify the src of image
动态修改图像的src

Vue.use(vueLazy, {
    filter: {
      progressive (listener, options) {
          const isCDN = /qiniudn.com/
          if (isCDN.test(listener.src)) {
              listener.el.setAttribute('lazy-progressive', 'true')
              listener.loading = listener.src + '?imageView2/1/w/10/h/10'
          }
      },
      webp (listener, options) {
          if (!options.supportWebp) return
          const isCDN = /qiniudn.com/
          if (isCDN.test(listener.src)) {
              listener.src += '?imageView2/2/format/webp'
          }
      }
    }
})

4.3、adapter

动态修改element的属性

Vue.use(vueLazy, {
    adapter: {
        loaded ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error, Init }) {
            // do something here
            // example for call LoadedHandler
            LoadedHandler(el)
        },
        loading (listender, Init) {
            console.log('loading')
        },
        error (listender, Init) {
            console.log('error')
        }
    }
})

4.4、observer与observerOptions

use Intersection Observer to to improve performance of a large number of nodes.

Vue.use(vueLazy, {
  // set observer to true
  observer: true,
 
  // optional
  observerOptions: {
    rootMargin: '0px',
    threshold: 0.1
  }
})

4.5、 lazyComponent

组件懒加载

//main.js
Vue.use(VueLazyload, {
  lazyComponent: true
});

//template
<lazy-component @show="handler">
  <img class="mini-cover" :src="img.src" width="100%" height="400">
</lazy-component>
 
<script>
  {
    ...
    methods: {
      handler (component) {
        console.log('this component is showing')
      }
    }
 
  }
</script> 

4.6、设置图片src

vue-lazyload will set this img element’s src with imgUrl string

vue-lazyload会通过imgUrl 字符串对img的src进行设置

<script>
export default {
  data () {
    return {
      imgObj: {
        src: 'http://xx.com/logo.png',
        error: 'http://xx.com/error.png',
        loading: 'http://xx.com/loading-spin.svg'
      },
      imgUrl: 'http://xx.com/logo.png' // String
    }
  }
}
</script> 
 
<template>
  <div ref="container">
     <img v-lazy="imgUrl"/>
     <div v-lazy:background-image="imgUrl"></div>
 
     <!-- with customer error and loading -->
     <img v-lazy="imgObj"/>
     <div v-lazy:background-image="imgObj"></div>
 
     <!-- Customer scrollable element -->
     <img v-lazy.container ="imgUrl"/>
     <div v-lazy:background-image.container="img"></div>
 
    <!-- srcset -->
    <img v-lazy="'img.400px.jpg'" data-srcset="img.400px.jpg 400w, img.800px.jpg 800w, img.1200px.jpg 1200w">
    <img v-lazy="imgUrl" :data-srcset="imgUrl' + '?size=400 400w, ' + imgUrl + ' ?size=800 800w, ' + imgUrl +'/1200.jpg 1200w'" />
  </div>
</template>

4.7、设置CSS状态

There are three states while img loading v

img 加载时的三种状态

loading loaded error

<img src="imgUrl" lazy="loading">
<img src="imgUrl" lazy="loaded">
<img src="imgUrl" lazy="error">
    
<style>
  img[lazy=loading] {
    /*your style here*/
  }
  img[lazy=error] {
    /*your style here*/
  }
  img[lazy=loaded] {
    /*your style here*/
  }
  /*
  or background-image
  */
  .yourclass[lazy=loading] {
    /*your style here*/
  }
  .yourclass[lazy=error] {
    /*your style here*/
  }
  .yourclass[lazy=loaded] {
    /*your style here*/
  }
</style> 

5、方法

vm.$Lazyload.$on(event, callback)

vm.$Lazyload.$off(event, callback)

vm.$Lazyload.$once(event, callback)

  • $on听一个自定义事件loadingloadederror
  • $once收听自定义事件,但仅一次。首次触发时,监听器将被删除。
  • $off 删除事件侦听器。

5.1、$on

vm.$Lazyload.$on

参数

  • {string} event
  • {Function} callback

示例

vm.$Lazyload.$on('loaded', function ({ bindType, el, naturalHeight, naturalWidth, $parent, src, loading, error }, formCache) {
  console.log(el, src)
})

5.2、$once

vm.$Lazyload.$once

参数

  • {string} event
  • {Function} callback

示例

vm.$Lazyload.$once('loaded', function ({ el, src }) {
  console.log(el, src)
})

5.3、$off

vm.$Lazyload.$off

If only the event is provided, remove all listeners for that event

如果只提供事件,则删除该事件的所有侦听器

参数

  • {string} event
  • {Function} callback

示例

function handler ({ el, src }, formCache) {
  console.log(el, src)
}
vm.$Lazyload.$on('loaded', handler)
vm.$Lazyload.$off('loaded', handler)
vm.$Lazyload.$off('loaded')

5.4、延迟加载处理程序

vm.$Lazyload.lazyLoadHandler

Manually trigger lazy loading position calculation

手动触发延迟加载位置计算

示例

this.$Lazyload.lazyLoadHandler()

控制台输出

this.$Lazyload.$on('loaded', function (listener) {
  console.table(this.$Lazyload.performance())
})

5.5、动态切换图片

 <img v-lazy =“ lazyImg”:key =“ lazyImg.src”>
 类似资料: