vue-lazyload具体使用细节

在vue中使用图片懒加载详细指南

说明

当网络请求比较慢的时候,提早给这张图片添加一个像素比较低的占位图片,不至于堆叠在一块,或显示大片空白,让用户体验更好一点。javascript

使用方式

使用vue的 vue-lazyload 插件
插件地址:html

https://www.npmjs.com/package/vue-lazyload 

案例

demo: 懒加载案例demovue

Installation 安装方式

npm

$ npm i vue-lazyload -D

CDN

CDN: https://unpkg.com/vue-lazyload/vue-lazyload.jsjava

<script src="https://unpkg.com/vue-lazyload/vue-lazyload.js"></script> <script> Vue.use(VueLazyload) ... </script> 

用法

main.js 在入口文件git

import Vue from 'vue' import App from './App.vue' import VueLazyload from 'vue-lazyload' //引入这个懒加载插件 Vue.use(VueLazyload) // 或者添加VueLazyload 选项 Vue.use(VueLazyload, { preLoad: 1.3, error: 'dist/error.png', loading: 'dist/loading.gif', attempt: 1 }) new Vue({ el: 'body', components: { App } })

在入口文件添加后,在组件任何地方均可以直接使用把 img 里的:src -> v-lazy

<div class="pic"> <a href="#"><img :src="'/static/img/' + item.productImage" alt=""></a> </div> 把以前项目中img 标签里面的 :src 属性 改为 v-lazy <div class="pic"> <a href="#"><img v-lazy="'/static/img/' + item.productImage" alt=""></a> </div>

参数选项说明

key description default options
preLoad proportion of pre-loading height 1.3 Number
error 当加载图片失败的时候 'data-src' String
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 component 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

想要监听的事件

您能够经过传递数组来配置想要使用vue - lazyload的事件
监听器的名字。github

 
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' ] })

若是您遇到这个插件从新设置加载的麻烦,这是颇有用的
当你有某些动画和过渡的时候。npm

转载自:https://segmentfault.com/a/1190000011672452segmentfault

相关文章
相关标签/搜索