超智能vue图片懒加载之指令化管理(vue-img-lazy-load)

2,247 阅读2分钟

分享一个基于vue的图片懒加载的指令插件,使用起来也是极其简易。 图片的懒加载,可以减少首页首次加载的数量,减少服务器的压力,优化用户体验,有点就不多提了,所以在app里使用图片懒加载是很必要的。

安装/Install

npm install vue-images-lazy-load --save

使用/Use

全局注册/Global registration (main.js)

import VueImgLazyLoad from 'vue-images-lazy-load';
// default
Vue.use(VueImgLazyLoader);
// options
Vue.use(VueImgLazyLoader, {
    observerOptions: {
	rootMargin: '0px 0px -400px 0px',
	threshold: 0.5
    },
    delayTime: 1000
});
options
  • oberserOptions: 观察者参数配置。
    rootMargin:可以区域范围,比如:"0px 0px -100px 0px",则为元素超出视窗底部100px被视为可见;默认'0px'
    threshold(0-1): 元素达到视窗设置的rootMargin,还要加上自身的百分比被视为可见;默认0
  • delayTime :给图片添加延时加载的时间,default: (500 + Math.random() * 500)
  • oberserOptions: observer parameter configuration.
    rootMargin:areas such as "0px 0px-100px 0px" are considered visible if the element exceeds 100px at the bottom of the window; default is'0px'.
    threshold(0-1):elements that reach the rootMargin of the window settings, plus their own percentages, are considered visible; default 0
  • delayTime : add a delay loading time to the picture,default: (500 + Math.random() * 500)

tips

最开始的名字有冲突,所以使用了vue-images-lazy-load
The initial name was conflicting, so vue-images-lazy-load was used.

局部注册/Partial registration (*.vue)

import { directive } from 'vue-images-lazy-load';
directives: {
    'img-lazy-load': directive
}

*.vue

使用默认配置/use default config
<img :src="baseUrl" v-img-lazy-load />

参数配置/Parameter configuration

  • url:替换插件默认的展位图,格式请用base64格式,或者提起解析好的(require,import),或者cdn地址
    url: Replace the default booth map of the plug-in, in base64 format, or mention parsed(require,import) or CDN address.
<img :src="baseUrl" v-img-lazy-load="{url: ''}" />

没有太多复杂的参数配置,使用起来非常简单轻便。如果觉得有点用的同学欢迎start,有什么问题也欢迎讨论,项目基于typescript,欢迎同学们查看。

项目地址:github.com/Vitaminaq/v…

使用的项目地址:github.com/Vitaminaq/c…(项目基于typescript,欢迎start)