vue图片懒加载

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue图片懒加载

Jiang_JY   2022-09-29 我要评论

1、安装vue-lazyload插件

npm install vue-lazyload --save-dev

2、在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
})

注意:

这里存在一个坑,当图片放在 assets文件下 的时候,要使用上面的这种 require(‘相对路径’)的写法来进行引入。当图片放在 static文件下 的时候就可以直接写路径来进行引入,像下面的写法一样。

static文件图片引入方法:

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

各个自定义配置属性含义:

keydescriptiondefaultoptions
preLoad预压高度比例1.3Number
errorsrc of the image upon load fail(指定加载失败时图片)‘data-src’String
loadingsrc of the image while loading(指定加载图片)‘data-src’String
attempt尝试计数3Number
listenEvents想要监听的事件[‘scroll’, ‘wheel’, ‘mousewheel’, ‘resize’, ‘animationend’, ‘transitionend’, ‘touchmove’]Desired Listen Events
adapter动态修改元素属性{ }Element Adapter
filter图片监听或过滤器{ }Image listener filter
lazyComponentlazyload 组件falseLazy Component
dispatchEvent触发dom事件falseBoolean
throttleWaitthrottle wait200Number
observeruse IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver options{ rootMargin: ‘0px’, threshold: 0.1 }IntersectionObserver
silentdo not print debug infotrueBoolean

3、使用(将图片设置为懒加载)

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

注意:

当遇到是v-for循环的时候,或者用div包裹着img的时候,需要在div上面添加 v-lazy-container="{ selector: ‘img’ }"

<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>

如果是这种情况的话,一定要使用 data-src 来指定路径,而不使用v-lazy。因为如果使用的是v-lazy的话,拿到了图片地址也会一直显示不出来。

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们