1.0.8 • Published 2 years ago

xyf_tools_js v1.0.8

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

xyf_tools_js

常用的一些js工具函数汇总,下面的函数会按照分类展示使用方式,都是按照按需导入的方式引用,完全不依赖第三方库


animate

一个js动画函数,可以控制动画的执行进度,通过prmise和await使用

Animator的参数定义 | 参数名称 | 类型 | 定义 | | :--------: | :-----: | :----: | |duration| number,默认值 2000|动画执行的时间 |update| (p: number,sourceN:number) => void|每一帧的执行回调 |easing| (n:number) => number|动画函数,处理每一帧之后的回调

使用方式

import  Animator  from 'xyf_tools_js/lib/animate'
const btn = document.getElementById('start')
const animator = new Animator(
2000,
(p,sourceP) => { // 随时间变化的回调值 sourceP  在 0 到 1之间  p 是经过第三个参数处理的值也就是 0 到 4
  const tx = -100 * Math.sin(2 * Math.PI * p);
  const ty = -100 * Math.cos(2 * Math.PI * p);
  // btn 是需要进行动画的元素
  btn.style.transform = "translate(" + tx + "px," + ty + "px)";
},
(p) => 4*p
);
btn.onclick = async () => {
await animator.animate();
console.log('动画执行完毕');
}

arr

1、flat数组的扁平化

import  arr  from 'xyf_tools_js/lib/arr'
var a = [[2,3],[[4,6]]]
console.log(arr.flat(a)); // [2, 3, 4, 6]

2、generateArr 生成指定长度的数组

 /**
 *
 * @param start 起始值
 * @param stop 结束值
 * @param step 步长
 * @returns
 */
  console.log(arr.generateArr(1,30,2));
 //[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]

blob

关于blobbase64filebufferimg之间的转化

import  * as blob  from 'xyf_tools_js/lib/blob'
// file 转化为 base64
const base = wait blob.imgToBase64(file) //file表示input选择的文件

// base64转化为blob
var blobObj = blob.convertBase64ToBlob(base64)

// base64转化为file
var file = blob.base64toFile(base64,'ceshi') // 第二个参数为文件名称,现在只支持图片类型的

//  blob转化为base64
var base64 = await blob.blobToBase64(blob)

// 将 http图片转化为 base64
const base =await blob.convertUrlToBase64('https://xxx/detail_bac.png')
//返回结果
> {
>     dataURL: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABdw
>     ext: "png"
>     height: 280
>     name: "detail_bac"
>     type: "image/png"
>     with: 1500
> }

// buffer 转化为 blob
var blob = blob.bufferToBlob(arrbuffer,type) // type 是 blob类型

browser

主要是和浏览器相关的一些原生api的使用

引入方式

import  * as browser   from 'xyf_tools_js/lib/arr'

1、全屏切换

var isScreen = browser.toggleFullscreen() // 返回值是当前的屏幕状态

注意:如果全屏之后是黑屏的话需要加上下面的css

:not(:root):fullscreen::backdrop{
      background-color: yellow !important;
}

2、滚动到指定元素

browser.smoothScroll(element) // 传入指定的元素

3、滚动到页面顶部

browser.scrollToTop()

4、复制文字内容

browser.copy('fasdf')

cookie

引入方式

import  * as cookie   from 'xyf_tools_js/lib/cookie'

1、设置cookie

cookie.setCookie(cname:string,cvalue:string,options = {
    path:"/",
    domain:window.location.hostname
})

2、获取cookie

cookie.getCookie(cname:string):string

3、删除所有cookie

cookie.delAllCookie(domain: string = document.domain)

debounce

防抖,在指定的时间范围内多次触发,只会在最后停止wait毫秒之后才会触发,例如根据用户搜索发送请求的时候

/**
 * 防抖 延迟几秒后执行
 * @param { function } func
 * @param { number } wait 延迟执行毫秒数
 */
debounce(func: () => void, wait: number)

diff

比较两个对象的不同

const a = {
a: 232,
b: 3,
c:{
  a:123
}
}
const pre = {
b: 3,
c:{
  a:'131'
}
}
// a表示当前的数据,c表示之前的数据
console.log(diff(a,pre)); //{a: 232, c.a: 123}

formCheck

多用于表单校验,目前只支持四种校验规则,下面是使用方法

 let rules = {
    phone: [
      { require: true, message: "请输入手机号码" },
      { pattern: /^(1[3584]\d{9})$/, message: "请输入正确的手机号码" },
    ],
    password: [
      { require: true, message: "请输入密码" },
      { minLength: 6, message: "密码长度最低6位数" },
      { maxLength: 10, message: "密码长度最长10位数" },
    ],
  };
  let params = {
    phone: "15208888888",
    password: "111133",
  };
  let a = new formCheck(rules, params);
  let message = a.start();
  console.log(message);

img

关于图片操作的一些方法

引入方式

import {
  compressImg,
  getOrientation,
  resetOrientation,
  downloadFile,
  downloadFileByBase64,
  captureVideo,
} from "xyf_tools_js/lib/img";

使用方式

1、downloadFile, downloadFileByBase64 直接下载文件

// 这个是下载网络图片
fetch('https://workyd.com/image/ydhl/detail_bac.png',{
      method:"get",
      responseType: 'blob'
}).then(res => {
  return res.blob()
}).then(blob => {
  const objectUrl = URL.createObjectURL(blob) // 生成一个url
  img.downloadFile(objectUrl,'ceshi.png')
})

// 必须是blob创建的url URL.createObjectURL(myBlob)
downloadFile(url, name)

//下载文件 base64文件的base64  name文件名称
downloadFileByBase64(base64, name)

2、获取视频的封面

其实就是对当前视频的一个截图,不一定是第一秒

/**
<video id="videoEL" controls autoplay crossorigin="anonymous"
  src="https://api.dogecloud.com/player/get.mp4?vcode=5ac682e6f8231991&userId=17&ext=.mp4" width="500"></video>
*/
captureVideo(videoEle)  // videoEle html节点元素,返回的是base64

3、图片压缩

// type OptionProp = {
//   scale: number; // 压缩比例 0-1,越小压缩越明显
//   size: number; // 表示的是多少M
// };
//  压缩图片
const base64 = await compressImg(file:File,options:OptionProp);

4、获取图片的旋转角度

getOrientation(file:File,callBack:Function)

5、将图片旋转到正确的角度

resetOrientation(base64: String, srcOrientation): Promise<string> 

num

避免小数点计算的时候出现精度问题 引入方式

import { accAdd, accSubtr, accMul, accDivCoupon } from "xyf_tools_js/lib/num";

使用方式

accAdd(1, 2, 3); //可以添加更多参数  加
accSubtr(4, 2); //   减
accMul(4, 2); //    乘
accDivCoupon(4, 2); //    除

obj

和对象有关的一些方法

引入方式

import { cloneDeep } from "xyf_tools_js/lib/obj";

使用方式

cloneDeep(object); //对象里面不能有函数

js 原生交互

js 调用原生方法

引入方式

import "xyf_tools_js/lib/jsBridge";

源码实现

/**
 * jsBridge 用于调用原生方法
 * window.jsNatives.dealFun()
 */
Function.prototype.getName = function () {
  return this.name || this.toString().match(/function\s*([^(]*)\(/)[1];
};
// 原生方法列表
let nativeMethods = [];
window.jsNatives = {
  isAndroid: false,
  initData() {
    const u = navigator.userAgent;
    const app = navigator.appVersion;
    const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; // g
    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios缁堢
    if (isAndroid) {
      this.isAndroid = true;
    } else {
      this.isAndroid = false;
    }
  },
  bindWindow(callBack) {
    if (callBack != null) {
      window[callBack.getName()] = callBack;
      callBack = callBack.getName();
    }
    return callBack;
  },
  /**
   *  api  原生函数名称
   * params {
   *   api  原生调用的回掉函数
   *   data   需要得参数json
   *   callBack  回掉函数
   * }
   */
  dealFun(api, params = {}) {
    try {
      if (params.callBack) {
        window[api] = params.callBack;
        params.callBack = api;
      }
      const param = JSON.stringify(params);
      if (this.isAndroid) {
        if (window.callNativeHandler) {
          window.callNativeHandler[api](param);
        }
      } else {
        window.webkit.messageHandlers[api].postMessage(param);
      }
    } catch (err) {
      console.log(err);
    }
  },
};
window.jsNatives.initData();

request 请求

引入方式

import request, { clearToken } from "xyf_tools_js/lib/request";

使用方式

如果是 postfile 请求,需改修改 file 的 key,可以在 data 里面添加 name 属性

/**
 * axios 请求库
 * options {
 *  method: get | delete | post | postfile | put | patch,
 *  data:  Object // 请求参数
 *  url:   string  // 请求的url
 *  headers:  Object  // 请求的header
 * }
 * userKey  默认值token  本次token的存储key
 * successCode 默认为0 数据成功返回时的code值
 */

const res = request(axios, options, userKey);

clearToken(); // 清除token 退出登录时调用

判断设备类型

检测挡墙的设备类型

引入方式

import { isPC, isIos, isWeiXin } from "xyf_tools_js/lib/systemCheck";

使用方式

isPC();
isIos();
isWeiXin();
isAndroid()

throttle

节流,在一定时间内只会触发一次,可以用于防止二次点击,或者频繁操作的事件,注意这种方式有可能最后一次会不执行

引入方式

import throttle from "xyf_tools_js/lib/throttle";

使用方式

const fun = throttle(() => {}, 2000);

time 方法

有关的时间格式化的处理方法

引入方式

import { dateFormat } from "xyf_tools_js/lib/time";

使用方式

/**
 *
 * @param {*} fmt  'yyyy-mm-dd HH:MM:SS'    2017-02-32
 * @param {*} date 要转化的日期
 */
const str = dateFormat(fmt: string, date: Date)

tree 方法

有关树的操作方法汇总以下的所有方法都会改变原始数组

引入方式

import {
  foreachTree,
  addTreePosition,
  createTree,
  filterTreeId,
} from "xyf_tools_js/lib/tree";

使用方式

1、foreachTree 遍历数组的每一项

/**
 *
 * @param {*} data  要操作的数组
 * @param {*} childrenName child的key
 * @param {*} callback 每一项都会进行操作的回调函数
 */
 foreachTree(data: any[],
  childrenName = "children",
  callback = (item: any) => {})

2、addTreePosition 将数组添加 position 属性,记录 key 的历史

/**
 * 将数组添加position属性,记录key的历史
 * @param {*} data  要操作的数组
 * @param {*} childrenName child的key
 * @param {*} idName position属性需要存储的key的值
 */
  var treeData = [
    {
      name:'1',
      children:[
        {
          name:'1-1',
          children:[
            {
              name:'1-1-1'
            },
            {
              name:'1-1-2'
            }
          ]
        },
        {
          name:'1-2',
          children:[
            {
              name:'1-2-1'
            },
            {
              name:'1-2-2'
            }
          ]
        }
      ]
    },
    {
      name:'2',
      children:[
        {
          name:'2-1',
          children:[
            {
              name:'2-1-1'
            }
          ]
        }
      ]
    },
  ]
  tree.addTreePosition(treeData,'children','name')
  console.log(treeData);

3、createTree 根据数组结构生成 tree

/**
 * 根据数组结构生成tree
 *  @param { object } items 后台获取的数据
 *  @param { * } link 生成树形结构的依据
 *  @param { * } id 数据中的id
 */
const a = [
  {
    id: "31",
    name: "fas000",
  },
  {
    id: "24",
    name: "fas122",
    pid: "31",
  },
  {
    id: "35",
    name: "fas",
  },
];
const temp = createTree(a, "pid", "id");

4、filterTreeId 根据指定 id 过滤数组中的数据

/**
 * 根据指定id过滤数组中的数据
 * @param items 传入的 数组
 * @param ids 返回指定id的数据
 */
const a = [
  {
    id: "31",
    name: "fas000",
    children: [
      {
        id: "24",
        name: "fas122",
        pid: "31",
      },
      {
        id: "35",
        name: "fas",
      },
    ],
  },
  {
    id: "389",
    name: "fas000",
    children: [
      {
        id: "240",
        name: "fas122",
        pid: "31",
      },
      {
        id: "354",
        name: "fas",
      },
    ],
  },
];

const temp = filterTreeId(a, ["389", "240", "24"]);
console.log(temp);

工具函数

引入方式

import { runPromises,formatMoney } from "xyf_tools_js/lib/time";

1、promise 按顺序执行

runPromises([pro1,peo2],initData) // initData 可以传入初始参数

2、formatMoney 将数字转化为千分位

formatMoney(num) // num 传入的数字

解决 hash 改变不跳转

window.addEventListener(
  "hashchange",
  () => {
    var currentPath = window.location.hash.slice(1); // 获取输入的路由
    if (this.$router.path !== currentPath) {
      this.$router.push(currentPath); // 动态跳转
    }
  },
  false
);
1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago