z-util-page v3.3.2
z-util-page 说明文档
简介
z-util-page 是一个基于JavaScript的工具包,包含了一些常用的工具函数,如防抖、节流、深拷贝等。
安装
1. 全局引入
拷贝包目录下dist文件夹内 zutilpage.min.js 文件到自己的项目里,在HTML里添加如下引用:
<script src="zutilpage.min.js"></script>这会添加一个全局变量 Utils 到window对象;
Utils.debounce(function(){
    console.log('身体和心灵,总有一个在路上。');
}, 200);2. 按需引入
运行以下命令将工具包安装到本地
npm i z-util-page --save根据需要自行引入
import { debounce, throttle, deepClone } from 'z-util-page';说明
Cookie操作辅助类
CookieHelper
clear()
function clear(): void清空cookie
Example
clear();Returns
void
exist()
function exist(key: string): boolean根据key值判断Cookie中是否存在键值对
Example
exist('test');Parameters
key
string
key值
Returns
boolean
getItem()
function getItem(key: string): string根据key值获取cookie数据
Example
getItem('test');Parameters
key
string
key值
Returns
string
Cookie中key值为key的值
getItemOnce()
function getItemOnce(key: string): string根据key值获取cookie数据后删除Cookie中该键值对
Example
getItemOnce('test');Parameters
key
string
key值
Returns
string
Cookie中键值为key的值
removeItem()
function removeItem(key: string): void根据key值删除Cookie中键值对
Example
removeItem('test');Parameters
key
string
key值
Returns
void
setItem()
function setItem(key: string, val: string): boolean设置cookie的键值对
Example
setItem('test', '你好, 世界!');Parameters
key
string
键
val
string
值
Returns
boolean
DOM操作辅助类
DomHelper
draggable()
function draggable(dom: HTMLElement): false | {
  close: void;
  open: void;
  wrap: void;
}将一个元素处理为可拖动元素
Example
const handle = draggable(dom: HTMLElement);
// 关闭拖动功能
handle.close();
// 开启拖动功能
handle.open();
// 指定一个子元素,当该鼠标按下该元素时,关闭拖动功能,鼠标抬起后恢复拖动功能
handle.wrap(dom: HTMLElement);Parameters
dom
HTMLElement
要处理的元素
Returns
false | {
  close: void;
  open: void;
  wrap: void;
 }
scrollToBottom()
function scrollToBottom(scroll: HTMLElement): void将可滚动元素滚动到底部
Example
scrollToBottom(dom: HTMLElement);Parameters
scroll
HTMLElement
要滚动的元素
Returns
void
scrollToLeft()
function scrollToLeft(scroll: HTMLElement): void将可滚动元素滚动到最左侧
Example
scrollToLeft(dom: HTMLElement);Parameters
scroll
HTMLElement
要滚动的元素
Returns
void
scrollToRight()
function scrollToRight(scroll: HTMLElement): void将可滚动元素滚动到最右侧
Example
scrollToRight(dom: HTMLElement);Parameters
scroll
HTMLElement
要滚动的元素
Returns
void
scrollToTop()
function scrollToTop(scroll: HTMLElement): void将可滚动元素滚动到顶部
Example
scrollToTop(dom: HTMLElement);Parameters
scroll
HTMLElement
要滚动的元素
Returns
void
HTTTP请求操作辅助类
Http
Constructors
new Http()
new Http(options: CustomHttpOptions): Http构造函数
Example
const http = new Http({
 //超时等待时间(ms)
 timeout: 10000,
 //基地址
 baseUrl: 'http://localhost:3000',
 //请求体数据格式
 contentType: 'application/json',
 //响应数据格式
 responseType: 'json'
});Parameters
options
CustomHttpOptions
默认参数
Returns
Http
Properties
| Property | Modifier | Type | Description | 
|---|---|---|---|
Interceptor | public | Interceptor | 拦截器 | 
options | public | HttpOptions | 默认参数 | 
Methods
ajax()
ajax(param: Param): PromiseHandleXMLHttpRequest异步请求
Example
const http = new Http();
// 拦截器
http.Interceptor.request((param) => {
 // 请求参数
 console.log(param);
 param.url = 'http://localhost:3000' + param.url;
})
http.Interceptor.response((res) => {
 // 请求结果
 console.log(res);
 res.data = res.data + '拦截器修改';
 return res;
})
// 请求
const req = http.ajax({
 // 请求地址
 baseUrl: 'http://localhost:3000',
 url: '/api/user',
 // 请求方法
 method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE',
 // 响应数据格式
 type: "arraybuffer" | "blob" | "document" | "json" | "text",
 // 请求头
 headers: {
  'Content-Type': 'application/json',
   'Authorization': 'Bearer ' + token
 }
 // 请求体
 data: {
  name: 'jack'
 }
 // 请求参数
 params: {
  name: 'jack'
 }
 // 请求超时时间
 timeout: 10000
 // 请求体数据格式
 contentType: 'application/json',
 // 响应数据类型
 responseType: 'json',
 // 上传文件
 file: {
   file: new Blob([JSON.stringify({a: '身体和心灵,总有一个在路上。'}, null, 2)], {type : 'application/json'})
 }
}).then((res) => {
  // 请求成功
}).catch((err) => {
 // 请求失败
}).finally(() => {
 // 请求完成
}).progress(() => {
 // 请求进度
});
// 取消请求
req.abort();Parameters
param
Param
请求参数
Returns
PromiseHandle
ajaxAsync()
ajaxAsync(param: Param): anyXMLHttpRequest同步请求,绝大多数情况下只能在work进程内使用。
Example
const http = new Http();
// 请求
const req = http.ajax({
 // 请求地址
 baseUrl: 'http://localhost:3000',
 url: '/api/user',
 // 请求方法
 method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE',
 // 响应数据格式
 type: "arraybuffer" | "blob" | "document" | "json" | "text",
 // 请求头
 headers: {
  'Content-Type': 'application/json',
   'Authorization': 'Bearer ' + token
 }
 // 请求体
 data: {
  name: 'jack'
 }
 // 请求参数
 params: {
  name: 'jack'
 }
 // 请求超时时间
 timeout: 10000
 // 请求体数据格式
 contentType: 'application/json',
 // 响应数据类型
 responseType: 'json',
 // 上传文件
 file: {
   file: new Blob([JSON.stringify({a: '身体和心灵,总有一个在路上。'}, null, 2)], {type : 'application/json'})
 }
})
// 请求成功
console.log(res);Parameters
param
Param
请求参数
Returns
any
indexedDB操作辅助类
IDBHelper
Constructors
new IDBHelper()
new IDBHelper(name: string): IDBHelper构造函数
Parameters
name
string
数据库名称
Returns
IDBHelper
IDBHelper实例
Throws
Error 数据库名称不能为空
Methods
close()
close(): Promise<undefined | false>关闭数据库
Example
const db = new IDBHelper('test');
await db.close();Returns
Promise\<undefined | false>
createTable()
createTable(tableNameList: string | string[], keyPath?: string): Promise<boolean>创建表
Example
const db = new IDBHelper('test');
await db.createTable('tn');Parameters
tableNameList
string | string[]
表名列表
keyPath?
string
主键
Returns
Promise\<boolean>
deleteAllTable()
deleteAllTable(): Promise<boolean>删除所有表
Example
const db = new IDBHelper('test');
await db.deleteAllTable();Returns
Promise\<boolean>
deleteTable()
deleteTable(tableNameList: string | string[]): Promise<boolean>删除表
Example
const db = new IDBHelper('test');
await db.deleteTable('tn');Parameters
tableNameList
string | string[]
表名列表
Returns
Promise\<boolean>
deleteTableRow()
deleteTableRow(tableName: string, key: string): Promise<undefined | false>删除表中某行数据
Example
const db = new IDBHelper('test');
await db.deleteTableRow('tn', 'key');Parameters
tableName
string
表名
key
string
键
Returns
Promise\<undefined | false>
getAllTableName()
getAllTableName(): Promise<false | DOMStringList>获取所有表名
Example
const db = new IDBHelper('test');
await db.getAllTableName();Returns
Promise\<false | DOMStringList>
false 或 string[]
getAllTableRow()
getAllTableRow(tableName: string, range?: IDBKeyRange): Promise<unknown>获取表中所有数据
Example
const db = new IDBHelper('test');
await db.getAllTableRow('tn');Parameters
tableName
string
表名
range?
IDBKeyRange
Returns
Promise\<unknown>
getTableRow()
getTableRow(tableName: string, key: string): Promise<unknown>获取表中某行数据
Example
const db = new IDBHelper('test');
await db.getTableRow('tn', 'key');Parameters
tableName
string
表名
key
string
键
Returns
Promise\<unknown>
getTableRowCount()
getTableRowCount(tableName: string, range?: IDBKeyRange): Promise<unknown>获取表数据条数
Example
const db = new IDBHelper('test');
await db.getTableRowCount('tn');Parameters
tableName
string
表名
range?
IDBKeyRange
Returns
Promise\<unknown>
reSet()
reSet(): Promise<false | Boolean>重置数据库
Example
const db = new IDBHelper('test');
await db.reSet();Returns
Promise\<false | Boolean>
setTableRow()
setTableRow(tableName: string, data: any): Promise<undefined | false>增加/修改表中某行数据
Example
const db = new IDBHelper('test');
await db.setTableRow('tn', '你好!');Parameters
tableName
string
表名
data
any
数据
Returns
Promise\<undefined | false>
事件总线
EventBus
Example
// 总线
let count = 0;
EventBus.on('test', function (num, num1) {
  count = num + num1;
})
EventBus.emit('test', 1, 2);
expect(count).toBe(3);
// 分线
let count = 0;
const bus = new EventBus();
bus.on('test', function (num, num1) {
  count = num + num1;
})
bus.emit('test', 3, 4);
expect(count).toBe(7);Constructors
new EventBus()
new EventBus(config?: EventBusConfig): EventBusParameters
config?
EventBusConfig
Returns
EventBus
Properties
| Property | Modifier | Type | 
|---|---|---|
emit | public | (key: string, ...rest: any[]) => void | 
on | public | (key: string, func: (...rest: any[]) => void) => void | 
Methods
emit()
static emit(key: string, ...rest: any[]): void触发事件
Parameters
key
string
事件名
...rest
any[]
传给回调函数的参数
Returns
void
on()
static on(key: string, func: (...rest: any[]) => void): void监听事件
Parameters
key
string
事件名
func
(...rest: any[]) => void
回调函数
Returns
void
响应式数据API
Reactive
computed()
function computed<T>(getter: () => {
  value: T;
 }): {
  get value: any;
}获取计算属性
Example
const count = ref(0);
const double = computed(() => count.value * 2);
console.log(double.value); //0
count.value = 1;
console.log(double.value); //2Type Parameters
T
Parameters
getter
() => { value: T; }
Returns
{
  get value: any;
}computed
| Name | Type | 
|---|---|
get value | any | 
effect()
function effect(func: Function, options: EffectOptions): Effect创建副作用函数
Example
const count = ref(0);
effect(() => {
 console.log(count.value);
})
count.value = 1;
// 打印1Parameters
func
Function
函数
options
EffectOptions
配置
Returns
Effect
effectFunc
reactive()
function reactive<T>(
   value: T, 
   isShadow: boolean, 
   isReadonly: boolean): T代理对象值,返回响应式数据
Example
const obj = reactive({name:'张三'});
obj.name = '李四';
console.log(obj.name); //李四Type Parameters
T extends object
Parameters
value
T
undefined
对象值
isShadow
boolean
false
true为深代理,false为浅代理
isReadonly
boolean
false
是否只读
Returns
T
ref()
function ref<T>(value: T, isReadonly: boolean): Ref<T>代理基本类型值,返回响应式数据
const obj = ref(3);
obj.value = 4;
console.log(obj.value); //4Type Parameters
T
Parameters
value
T
undefined
基本类型值
isReadonly
boolean
false
是否只读
Returns
Ref\<T>
toRaw()
function toRaw<T>(proxy: T): T获取原始对象
Example
const count = reactive({ a: 1 });
console.log(toRaw(count)); //{ a: 1 }Type Parameters
T
Parameters
proxy
T
响应式对象
Returns
T
原始对象
toRef()
function toRef(val: any, key: string | symbol): {
  get set value: any;
}将响应式对象的某键值转为ref
Example
const obj = reactive({ a: 1 });
const a = toRef(obj, 'a');
a.value = 2;
console.log(obj.a); //2Parameters
val
any
响应式对象
key
string | symbol
键值
Returns
{
  get set value: any;
}Ref
| Name | Type | 
|---|---|
get value | any | 
set value | void | 
toRefs()
function toRefs(obj: any): {}将响应式对象的键值全部转换为Ref, 可解构使用
Example
const obj = reactive({ a: 1, b: 2 });
const { a, b } = toRefs(obj);
a.value = 2;
console.log(obj.a); //2Parameters
obj
any
响应式对象
Returns
{}Refs
watch()
function watch(
   source: object | Function, 
   cb: Function, 
   options: EffectOptions): void监听响应式数据
Example
const count = ref(0);
watch(count, (newVal, oldVal) => {
 console.log(newVal, oldVal);
})
count.value = 1;
// 打印1 0Parameters
source
object | Function
副作用函数或者响应式对象
cb
Function
数据变化后回调函数
options
EffectOptions
配置
Returns
void
文件操作辅助类
FileHelper
choose()
function choose(options: {
  accept: string[];
  capture:   | "user"
     | "environment"
     | "camera"
     | "camcorder"
     | "microphone";
  multiple: boolean;
}): Promise<FileList>文件选择
Example
choose({
 accept: [".doc",".docx","application/msword"],
 capture: "user",
 multiple: true
}).then(files => {
    console.log(files);
  })
  .catch(err => {
    console.error(err);
  });Parameters
options
object
文件选择配置
options.accept?
string[]
以逗号为分隔的唯一文件类型说明符列表
options.capture?
 | "user" | "environment" | "camera" | "camcorder" | "microphone"
尝试请求使用设备的媒体捕获设备(如:摄像机),而不是请求一个文件输入。camera–照相机;camcorder–摄像机;microphone–录音
options.multiple?
boolean
是否允许多选
Returns
Promise\<FileList>
pickDir()
function pickDir(dirKey: string, force: boolean): Promise<{
  data: FileSystemDirectoryHandle | null;
  message: string;
  success: boolean;
}>选择文件夹(与saveFileToDir共用缓存)
Example
//选择文件夹,将其与key绑定
pickDir('key');
//强制重新选择
pickDir('key', true);Parameters
dirKey
string
undefined
文件夹唯一标识,自行定义string,用于后续向同一文件夹写入文件
force
boolean
false
是否强制重新选择
Returns
Promise\<{
  data: FileSystemDirectoryHandle | null;
  message: string;
  success: boolean;
 }>
| Name | Type | 
|---|---|
data | FileSystemDirectoryHandle | null | 
message | string | 
success | boolean | 
read()
function read(file: Blob | File): FileReaderDecorate文件读取
Example
const reader = read(file)
 .loadend((res) => {
   console.log(res);
 })
 //start方法参数类型:"ArrayBuffer" | "BinaryString" | "DataURL" | "Text"
 .start("ArrayBuffer");
//读取操作发生中断时触发
reader.abort((abo) => {
  console.log(abo);
})
//读取操作发生错误时触发
reader.error((err) => {
  console.log(err);
})
//读取操作完成时触发
reader.load((res) => {
  console.log(res);
})
//读取操作开始时触发
reader.loadstart((res) => {
  console.log(res);
})
//读取操作结束时(要么成功,要么失败)触发
reader.loadstart((res) => {
  console.log(res);
})
//获取读取结果的promise
const promise = reader.loadendPromise();
//在读取Blob时触发。
reader.progress((res) => {
  console.log(res);
})
//获取状态
const status = reader.getStatus();
//获取结果
const result = reader.getResult();
//中断读取
reader.stop();Parameters
file
Blob | File
File对象或Blob对象
Returns
FileReaderDecorate
save()
function save(file: string | Blob, saveFileName: string): voidH5文件下载方法
Example
save(new Blob(['你好世界'], { type: 'text/plain' }), 'test.txt');
save('https://www.baidu.com/img/flexible/logo/pc/result@2.png', 'baidu.png');Parameters
file
string | Blob
undefined
资源链接或者blob对象
saveFileName
string
''
保存文件名
Returns
void
saveFileToDir()
function saveFileToDir(
   dirKey: string, 
   fileName: string, 
   fileContent: (FileContent | Promise<FileContent>)[], 
   overwrite: boolean): Promise<{
  message: string;
  success: boolean;
}>将文件写入目标文件夹
Example
//需要先调用pickDir选择文件夹
saveFileToDir('key', 'file.txt', ['string', new Blob(['你好世界'], { type: 'text/plain' })]);Parameters
dirKey
string
undefined
文件夹唯一标识,自行定义string,用于后续向同一文件夹写入文件
fileName
string
undefined
文件名
fileContent
(FileContent | Promise\<FileContent>)[]
undefined
二进制文件流或字符串数组
overwrite
boolean
true
是否覆盖同名文件
Returns
Promise\<{
  message: string;
  success: boolean;
 }>
| Name | Type | 
|---|---|
message | string | 
success | boolean | 
辅助函数
debounce()
function debounce(
   func: Function, 
   wait: number, 
   immediatel?: boolean): (this: any, ...args: any[]) => any将函数处理为防抖函数
Example
let debounced = debounce(function () {
  console.log('身体和心灵,总有一个在路上。');
  return '身体和心灵,总有一个在路上。';
}, 1000, true);
debounced.then(function (res) {
  console.log(res);
});
debounced();
debounced.cancel();Parameters
func
Function
待处理函数
wait
number
函数执行延迟时间
immediatel?
boolean
是否立刻执行
Returns
Function
处理好的防抖函数
Parameters
this
any
执行上下文继承自传入函数
...args
any[]
参数继承自传入函数
Returns
any
| Name | Type | Description | 
|---|---|---|
cancel | void | 取消防抖函数执行 | 
then | { (this: any, ...args: any[]): any; cancel(): void; then(callback: Function): ...; } | 注册防抖函数执行后的回调 | 
deepClone()
function deepClone(value: any): any深拷贝
Example
let newValue = deepClone({
  a: '身体和心灵,总有一个在路上。',
  b: {
    c: new Date(),
    d: [1, 3, 4],
    e: Symbol(),
    a: null,
    b: undefined,
    f: {
      a: 1,
      b: true,
    }
  },
  c: document.createElement('div'),
  d: new RegExp(/\d+/ig),
  e: new Error('错误'),
  f: function () {
    console.log('身体和心灵,总有一个在路上。');
  }Parameters
value
any
待克隆值
Returns
any
克隆值
generateUUID()
function generateUUID(length?: number, radix?: number): string生成UUID4
Example
generateUUID();
generateUUID(12, 32);Parameters
length?
number
生成uuid的总长度,不传递则按照rfc4122标准生成uuid
radix?
number
uuid每个字符的基数 1-62
Returns
string
uuid字符串
getType()
function getType(value: any): string获取数据类型
Example
const type = getType('你好');
type === 'String';Parameters
value
any
任意值
Returns
string
类型字符串, 如'String'、'Map'等
mergeObject()
function mergeObject<T>(
   origin: T, 
   ob: undefined | StandardObject, ...
   more: StandardObject[]): T深度合并n个对象值
Example
const a = { a: 1, b: { c: 2 } };
const b = { b: { d: 3 } };
const c = { c: 4 };
mergeObject(a, b, c);Type Parameters
T extends StandardObject
Parameters
origin
T
将多个对象深度合并到该对象
ob
undefined | StandardObject
被合并对象
...more
StandardObject[]
其余被合并对象
Returns
T
parseUrl()
function parseUrl(url: string): URLWithParam | null解析URL
Example
const url = 'https://www.baidu.com/s?wd=hello#world'
const result = parseUrl(url)Parameters
url
string
统一资源定位符
Returns
URLWithParam | null
throttle()
function throttle(
   func: Function, 
   wait: number, 
   option?: throttleOptions): (this: any, ...argList: any[]) => any函数节流
Example
interface throttleOptions {
  // 首次是否执行
  leading: boolean,
  // 结束是否执行
  trailing: boolean
}
let throttle = throttle(function(){
  console.log('身体和心灵,总有一个在路上。');
  return '身体和心灵,总有一个在路上。';
}, 1000, {
  leading: true, 
  trailing: true
});
throttle();
throttle.cancel();Parameters
func
Function
待处理函数
wait
number
函数执行最短间隔时间
option?
throttleOptions
函数执行配置
Returns
Function
处理好的节流函数
Parameters
this
any
执行上下文继承自传入函数
...argList
any[]
参数继承自传入函数
Returns
any
| Name | Type | Description | 
|---|---|---|
cancel | void | 取消节流函数执行 | 
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago