Lazy loading of images in vue

1. Install the vue-lazyload plugin

npm install vue-lazyload --save-dev

2. Reference in main.js

import VueLazyload from "vue-lazyload";
 
Vue.use(VueLazyload);

//或者自定义配置插件
Vue.use(VueLazyload, {
    
    
preLoad: 1.3,
error: require('../src/assets/image/error.png'),
loading: require('../src/assets/image/loading.gif'),
attempt: 1
})

Note:
There is a pitfall here. When the image is placed under the assets file , the above require('relative path') writing method should be used to import it. When the picture is placed under the static file, you can directly write the path to import it, as shown below.

Static file image import method:

Vue.use(VueLazyload, {
    
    
preLoad: 1.3,
error: '../src/assets/image/error.png',
loading: '../src/assets/image/loading.gif',
attempt: 1
})

The meaning of each custom configuration property:

key description default options
preLoad Preload height ratio 1.3 Number
error src of the image upon load fail (specify the image upon load failure) ‘data-src’ String
loading src of the image while loading (specify loading image) ‘data-src’ String
attempt try count 3 Number
listenEvents the event you want to listen to [‘scroll’, ‘wheel’, ‘mousewheel’, ‘resize’, ‘animationend’, ‘transitionend’, ‘touchmove’] Desired Listen Events
adapter Dynamically modify element attributes { } Element Adapter
filter Image monitoring or filter { } Image listener filter
lazyComponent lazyload component false Lazy Component
dispatchEvent trigger 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

3. Use (set the image as lazy loading)

<img v-lazy="psdimg" class="psd" />

Note:
When encountering a v-for loop, or wrapping an img with a div, you need to add v-lazy-container="{ selector: 'img' }" above the div

<div v-lazy-container="{ selector: 'img' }">
  <img data-src="//aaa.com/img1.jpg">
  <img data-src="//aaa.com/img2.jpg">
  <img data-src="//aaa.com/img3.jpg">  
</div>
  
<!--或者这种:-->
 
 <div v-lazy-container="{ selector: 'img' }" v-html="content">
</div>

If this is the case, be sure to use data-src to specify the path instead of v-lazy. Because if you use v-lazy, you will not be able to display the image address after getting it.

Guess you like

Origin blog.csdn.net/jiangjunyuan168/article/details/124278948