# 使用指南

作者: 谭辉

# 安装

通过包管理器安装:

npm install @dist/utils 或者 yarn add @dist/utils

使用: import { xxx } from @dist/utils

  • 支持 tree-shaking

  • 支持按需引入

    需要使用 babel 插件babel-plugin-import

    // babel.config.js
    module.exports = {
      plugins: [
        [
          'import',
          {
            libraryName: '@dist/utils',
            style: false,
            camel2DashComponentName: false,
            customName(name, file) {
              name = name[0].toLowerCase() + name.substr(1);
              return `@dist/utils/dist/es/${name}`;
            }
          }
        ]
      ]
    };
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

# Api 使用文档

# Array

# deepFind

深度查找,用法如Array.find,支持嵌套数组的查找。采用深度优先遍历进行查找。

deepFind(source: any[], predicate: (value, index, arr) => boolean)

例:deepFind(['1',['2',['3_1']],'3_2','4'], (val) => val.startsWith('3')), 查找结果为: '3_1'

# Object

# traverse

对象遍历,支持树状结构遍历, 采用深度遍历顺序。

traverse(target: Object, childrenkey?='children', callback: (node, parentNode) => any)

  • childrenKey:可选参数,表示元素后代属性,默认值为 children
  • callback: 必要参数,遍历每一个节点都会调用此回调函数,接收参数:node: 当前节点,parentNode: 父节点

例:

const obj = {
  name: parent,
  children: [{ name: 'child' }]
};
traverse(obj, (node, parent) => {
  console.log(node.name);
}); // parent, child
1
2
3
4
5
6
7

# Number

# convertUnit

单位转换工具,目前支持长度单位(米、千米),面积单位(平方米、平方千米、公顷、亩、万亩),当输入的单位不支持,或者单位间无法互相转换,返回 null。

covertUnit(input: number, from: string, to: string)

  • input:原单位数字
  • from: 原来的单位
  • to: 目标单位

例:convertUnit(1000, '米', '千米') === 1

# fixNumber

保留目标位数的数字小数位 ,不进行四舍五入。

fixNumber(num: number, precesion: number)

例:fixNumber(3.14159, 4) === 3.1415

# toThousands

将数字转换为千分位字符串表示。

toThousands(num: number): string

例:

toThousands(12345678); // 12,345,678
1

# Url

# encodeURL

对 URL 中的查询参数进行编码,如www.baidu.com?q=工具&k=c# 编码为www.baidu.com?q=%E5%B7%A5%E5%85%B7&k=c%23

encodeURL(url: string, appendParams?: {[p:string]: string|number})

  • appendParams: 可选,追加到 URL 中的查询参数

    // www.baidu.com?q=1&k=2
    encodeURL('www.baidu.com?q=1', { k: 2 });
    
    1
    2

# getSearchParams

获取 URL 中的查询参数,返回值为包含查询参数的键值对的对象。

getSearchParams(url: string)

例:

getSearchParams('www.baidu.com?q=工具&k=c#'); //{ q: '工具', k: 'c#' }
// 编码后的URL也可以解析
getSearchParams('www.baidu.com?q=%E5%B7%A5%E5%85%B7&k=c%23'); //{ q: '工具', k: 'c#' }
1
2
3

# browser

# Storage

localStoragesessionStorage的增强,其setItemgetItem方法将自动对值进行 JSON 序列化和反序列化。

Storage.local: 即localStorage,用法与原生一致

Storage.session: 即sessionStorage,用法与原生一致

Storage.setItem('user', { name: 1, age: 2 });
Storage.getItem('user'); // {name: 1, age: 2}
1
2

# 文件下载

# blobToFile

将 blob 类型数据下载至本地。支持 IE 浏览器

blobToFile(bolb: Blob, filename?:string)

# downloadByURL

创建 a 标签对给出的 URL 进行资源下载。支持 IE 浏览器

downloadByURL(url: string, filename: string)

# 数据判断

# hasChildren

判断元素是否具有 children 属性。

hasChildren(o: object, childrenKey?: string)

childrenKey默认值为:children

# isDef

判断值是否为undefinednull

isDef(v: any)

# isUndef

判断值是否不为undefinednull

isUndef(v: any)

# 环境判断

# isDev

判断process.env.NODE_ENV === 'developmen'

isDev(): boolean

# isIE

判断是否是 IE 浏览器

isIE(): boolean

# isMicroApp

判断是否是微前端环境(qiankun)

isMicroApp(): boolean

# isMobile

判断是否是移动端环境

isMobile(): boolean

# 其他

# loadScript

用于加载在线 js 资源,通过 script 标签的方式加载。返回一个Promise

loadScript(url: string, attributes?: object, onSuccess?: function, onError?: function): Promise

  • url - 资源地址
  • attributes - 可选,需要设置在 script 标签上的一些特性
  • onSuccess - 可选,接收 event 对象,当资源加载成功后调用
  • onError - 可选,接收一个错误对象,当资源加载失败后调用

可以通过回调的方式跟踪加载状态,也可以直接通过返回的 Promise 获取加载状态。

loadScript('cdn.com/deliver.js', ()=>console.log(success), () => console.log('error'))
// 可传递attributes给script标签
loadScript('cdn.com/deliver.js', {autoLogin: true}, () => console.log('success'), () => console.log('error'))

// 使用promise特性
loadScript('cdn.com/deliver.js').then((e)=>{ //todo }, (error) => {// todo })
1
2
3
4
5
6

# Polling

轮询,Polling为 class 构造函数。

new Polling(callback: function, time: number, immediate: boolean)

  • callback - 轮询函数
  • time - 轮询间隔,默认为 1000ms
  • immediate - 是否立即执行轮询, 默认为 false。后续通过手动调用实例上的start方法开始轮询

返回polling实例, 实例具有以下方法:

  • start - 开始轮询
  • cancel - 取消轮询

# rawTypeof

判断数据类型。其内部使用Object.prototype.toString方法

rawTypeof(v:any): string

返回的类型值为全小写字符

例:

  • rawTypeof([]) - array
  • rawTypeof(1) - object
  • rawTypeof({}) - object
  • rawTypeof(/\w/) - regexp

# 旧版 Utils 迁移

注:为了从老版本平滑升级,以下标注删除线的函数仍然包含在新版 utils 中,但不推荐继续使用,后期也不再维护。

# cachedFn

旧版中cachedFn并未正确实现函数缓存功能,建议使用lodash.memoize代替

# Http

旧版中对axios的封装过于简单,且axios本身适用性非常高,无需一个统一的封装层,由使用者自行实现。新版不再维护,不推荐继续使用。

注:如需继续使用此导出,需要自行安装 axios,此版本中 axios 作为 peerDependencies 引入

# isDev

与新版使用完全一致

# isIE

与新版使用完全一致

# isMicroApp

与新版使用完全一致

# localStorage

使用新版Storage.local

# sessionStorage

使用新版Storage.session

# verifyAuthority

针对项目具体接口数据的处理,目前主要在基础信息平台中使用,不建议继续使用

# formatDateByGreenwich

时间格式化。建议使用dayjs进行处理

# getPublicPath

针对微前端体系中主应用与微应用获取publicPath的方法