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 })
各个自定义配置属性含义:
key description default options preLoad 预压高度比例 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 尝试计数 3 Number listenEvents 想要监听的事件 [‘scroll’, ‘wheel’, ‘mousewheel’, ‘resize’, ‘animationend’, ‘transitionend’, ‘touchmove’] Desired Listen Events adapter 动态修改元素属性 { } Element Adapter filter 图片监听或过滤器 { } Image listener filter lazyComponent lazyload 组件 false Lazy Component dispatchEvent 触发dom事件 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、使用(将图片设置为懒加载)
<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的话,拿到了图片地址也会一直显示不出来。
总结
到此这篇关于vue项目实现图片懒加载的文章就介绍到这了,更多相关vue图片懒加载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于vue项目实现图片懒加载的简单步骤的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did121286