实现Vue图片懒加载

625 阅读2分钟

这是我参与8月更文挑战的第16天,活动详情查看:8月更文挑战 ! src=http___www.jisuxia.com_uploadfile_2020_0120_20200120013609531.jpg&refer=http___www.jisuxia.jfif

定义

延迟加载图片或符合某些条件时才加载某些图片

原理

在图片没有进入可视区域时,先不给的src赋值,这样浏览器就不会发送请求了,等到图片进入可视区域再给src赋值

目的

减少不必要的访问数据库或延迟访问数据库的次数,因为每次访问数据库都是比较耗时的即只有真正使用该对象的数据时才会创建。懒加载的主要目的是作为服务器前端的优化,减少请求数或延迟请求数

懒加载的优点

  1. 可以减少首页首次加载的数量,减少服务器的压力
  2. 当网络请求比较慢的时候, 提前给这张图片添加一个像素比较低的占位图片,提高用户体验

运用场景

如果一个页面需要好多图片需要加载,页面会变得非常的卡顿,此时如果只是可视区域的图片加载,其他的图片可以暂时有一个占位 loading 图,等滚动它们到可视区域时再去请求真实图片并且替换就好了

vue中如何使用

使用vue-lazyload 插件

(1)安装插件

npm install vue-lazyload --save-dev

(2)在入口文件 man.js 中引入并使用

import VueLazyload from 'vue-lazyload'

然后再 vue 中直接使用

Vue.use(VueLazyload)

或者添加自定义选项

Vue.use(VueLazyload, {
    preLoad: 1.3,
    error: 'dist/error.png',//图片路径错误时加载图片
    loading: 'dist/loading.gif',//预加载图片
    attempt: 1
})

下表为vue-lazyload详细api:

keydescriptiondefaultoptions
preLoadproportion of pre-loading height(预加载高度比例)1.3Number
errorsrc of the image upon load fail(图片路径错误时加载图片)'data-src'String
loadingsrc of the image while loading(预加载图片)'data-src'String
attemptattempts count(尝试加载图片数量)3Number
listenEventsevents that you want vue listen for(想要监听的vue事件)默认['scroll']可以省略,当插件跟页面中的动画或过渡等事件有冲突是,可以尝试其他选项['scroll'(默认),``'wheel',``'mousewheel',``'resize',``'animationend',``'transitionend',``'touchmove']Desired Listen Events
adapterdynamically modify the attribute of element(动态修改元素属性){ }Element Adapter
filterthe image's listener filter(动态修改图片地址路径){ }Image listener filter
lazyComponentlazyload componentfalseLazy Component
dispatchEventtrigger the dom eventfalseBoolean
throttleWaitthrottle wait200Number
observeruse IntersectionObserverfalseBoolean
observerOptionsIntersectionObserver options{ rootMargin: '0px', threshold: 0.1 }IntersectionObserver

(3)在 vue 文件中将 img 标签的 src 属性直接改为 v-lazy ,从而将图片显示方式更改为懒加载显示: <img v-lazy="/static/img/1.png">