github项目地址: https://github.com/murongg/vue3-lazyload
求star 与 issues
我文采不好,可能写的文章不咋样,有什么问题可以在留言区评论,我会尽力解答
本项目已经发布到npm
安装:
$ npm i vue3-lazyload
# or
$ yarn add vue3-lazyload
需求分析
-
支持自定义 loading 图片,图片加载状态时使用此图片
-
支持自定义 error 图片,图片加载失败后使用此图片
-
支持 lifecycle hooks,类似于 vue 的生命周期,并同时在
img
标签绑定lazy
属性,类似于<img src="..." lazy="loading"> <img src="..." lazy="loaded"> <img src="..." lazy="error">
并支持:
img[lazy=loading] { /*your style here*/ } img[lazy=error] { /*your style here*/ } img[lazy=loaded] { /*your style here*/ }
-
支持使用
v-lazy
自定义指令,指定可传入 string/object ,当为 string 时,默认为需要加载的 url,当为 object 时,可传入src:
当前需要加载的图片 urlloading:
加载状态时所用到的图片error:
加载失败时所用到的图片lifecycle:
本次 lazy 的生命周期,替换掉全局生命周期
目录结构
- src
---- index.ts 入口文件,主要用来注册插件
---- lazy.ts 懒加载主要功能
---- types.ts 类型文件,包括 interface/type/enum 等等
---- util.ts 共享工具文件
编写懒加载类
懒加载主要通过 IntersectionObserver
对象实现,可能有些浏览器不支持,暂未做兼容。
确定注册插件时传入的参数
types.ts
:
export interface LazyOptions {
error?: string; // 加载失败时的图片
loading?: string; // 加载中的图片
observerOptions?: IntersectionObserverInit; // IntersectionObserver 对象传入的第二个参数
log?: boolean; // 是否需要打印日志
lifecycle?: Lifecycle; // 生命周期 hooks
}
export interface ValueFormatterObject {
src: string,
error?: string,
loading?: string,
lifecycle?: Lifecycle;
}
export enum LifecycleEnum {
LOADING = 'loading',
LOADED = 'loaded',
ERROR = 'error'
}
export type Lifecycle = {
[x in LifecycleEnum]?: () => void;
};
确定类的框架
vue3 的 Custom Directives,支持以下 Hook Functions:beforeMount
、mounted
、beforeUpdate
、updated
、beforeUnmount
、unmounted
,具体释义可以去 vue3 文档查看,目前仅需要用到mounted
、updated
、unmounted
,这三个 Hook。
Lazy
类基础框架代码,lazy.ts
:
export default class Lazy {
public options: LazyOptions = {
loading: DEFAULT_LOADING,
error: DEFAULT_ERROR,
observerOptions: DEFAULT_OBSERVER_OPTIONS,
log: true,
lifecycle: {
}
};
constructor(options?: LazyOptions) {
this.config(options)
}
/**
* merge config
* assgin 方法在 util.ts 文件内,此文章不在赘述此方法代码,可在后文 github 仓库内查看此代码
* 此方法主要功能是合并两个对象
*
* @param {*} [options={}]
* @memberof Lazy
*/
public config(options = {