前端vue,js封装常用的各种方法,处理数组,对象,深拷贝,随机数,判断等等

前端js在项目中封装各种常用的方法

  • 关于使用
    • 1.存取sessionStorage
    • 2.存取localStorage
    • 3.生成随机数和字母
    • 4.数组和对象深拷贝
    • 5.菜单数据组织
    • 6.阿拉伯数字转中文
    • 7.数字补0占位
    • 8.时间戳转化为 YY-MM-DD HH:mm:ss
    • 9.ajax错误处理
    • 10.文件大小换算
    • 11.下载文件
    • 12.图片、文件url对http的处理
    • 13.列表转树状
    • 14.数组去重
    • 15.数组对象去重
    • 16.数组按某一属性分组
    • 17.html实体字符转标签
    • 18.过滤掉html的图片和其他标签
    • 19.获取对象key并返回数组
    • 20. 防抖
    • 20. 判断手机号
    • 21. 判断邮箱
    • 22. 判断是否是移动端
    • 23. 判断是微信、企业微信、钉钉

关于使用

直接拿去用或者自己封装起来

如果有对参数和方法使用不懂的欢迎下方留言

1.存取sessionStorage

//sessionStorage
export const session = function (key, value) {
     
  if (value === void 0) {
     
    const lsVal = sessionStorage.getItem(key);
    if (lsVal && lsVal.indexOf("autostringify-") === 0) {
     
      return JSON.parse(lsVal.split("autostringify-")[1]);
    } else {
     
      return lsVal;
    }
  } else {
     
    if (typeof value === "object" || Array.isArray(value)) {
     
      value = "autostringify-" + JSON.stringify(value);
    }
    return sessionStorage.setItem(key, value);
  }
};

2.存取localStorage

//localStorage
export const local = function (key, value) {
     
  if (value === void 0) {
     
    const lsVal = localStorage.getItem(key);
    if (lsVal && lsVal.indexOf("autostringify-") === 0) {
     
      return JSON.parse(lsVal.split("autostringify-")[1]);
    } else {
     
      return lsVal;
    }
  } else {
     
    if (typeof value === "object" || Array.isArray(value)) {
     
      value = "autostringify-" + JSON.stringify(value);
    }
    return localStorage.setItem(key, value);
  }
};

3.生成随机数和字母

//生成随机数
export const getUUID = function (len) {
     
  len = len || 6;
  len = parseInt(len, 10);
  len = isNaN(len) ? 6 : len;
  const seed = "0123456789abcdefghijklmnopqrstubwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ";
  const seedLen = seed.length - 1;
  let uuid = "";
  while (len--) {
     
    uuid += seed[Math.round(Math.random() * seedLen)];
  }
  return uuid;
};

4.数组和对象深拷贝

//深拷贝
export const deepcopy = function (source) {
     
  if (!source) {
     
    return source;
  }
  const sourceCopy = source instanceof Array ? [] : {
     };
  for (const item in source) {
     
    sourceCopy[item] =
      typeof source[item] === "object" ? deepcopy(source[item]) : source[item];
  }
  return sourceCopy;
};

5.菜单数据组织

//菜单数据组织
export const buildMenu = function (array, ckey) {
     
  const menuData = [];
  const indexKeys = Array.isArray(array) ?
    array.map(e => {
     
      return e.id;
    }) : [];
  ckey = ckey || "parent_id";
  array.forEach(function (e) {
     
    //一级菜单
    if (!e[ckey] || e[ckey] === e.id) {
     
      delete e[ckey];
      menuData.push(deepcopy(e)); //深拷贝
    } else if (Array.isArray(indexKeys)) {
     
      //检测ckey有效性
      const parentIndex = indexKeys.findIndex(function (id) {
     
        return id == e[ckey];
      });
      if (parentIndex === -1) {
     
        menuData.push(e);
      }
    }
  });
  const findChildren = function (parentArr) {
     
    if (Array.isArray(parentArr) && parentArr.length) {
     
      parentArr.forEach(function (parentNode) {
     
        array.forEach(function (node) {
     
          if (parentNode.name === node[ckey]) {
     
            if (parentNode.children) {
     
              parentNode.children.push(node);
            } else {
     
              parentNode.children = [node];
            }
          }
        });
        if (parentNode.children) {
     
          findChildren(parentNode.children);
        }
      });
    }
  };
  findChildren(menuData);
  return menuData;
};

6.阿拉伯数字转中文

//阿拉伯数字转中文
const SectionToChinese = (section) => {
     
  var chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  var chnUnitChar = ["", "十", "百", "千", "万", "亿", "万亿", "亿亿"];
  var strIns = '',
    chnStr = '';
  var unitPos = 0;
  var zero = true;
  while (section > 0) {
     
    var v = section % 10;
    if (v === 0) {
     
      if (!zero) {
     
        zero = true;
        chnStr = chnNumChar[v] + chnStr;
      }
    } else {
     
      zero = false;
      strIns = chnNumChar[v];
      strIns += chnUnitChar[unitPos];
      chnStr = strIns + chnStr;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return chnStr;
};

7.数字补0占位

//数字补零占位
export const addZero = function (t) {
     
  if (parseInt(t) < 10) {
     
    return "0" + t;
  } else {
     
    return t;
  }
};

8.时间戳转化为 YY-MM-DD HH:mm:ss

//时间戳转化
export const timestampToTime = function (timestamp) {
     
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = addZero(date.getDate()) + ' ';
  var h = addZero(date.getHours()) + ':';
  var m = addZero(date.getMinutes());
  var s = addZero(date.getSeconds());
  return Y + M + D + h + m + ':' + s;
};

9.ajax错误处理

//ajax错误处理
export const catchError = function (error) {
     
  if (error.data) {
     
    error = error.data;
  };
  if (error && error.message) {
     
    switch (error.code) {
     
      case 400:
        Vue.prototype.$message({
     
          message: error.message || "请求参数异常",
          type: "error"
        });
        break;
      case 500:
        Vue.prototype.$message({
     
          message: error.message || "服务器异常",
          type: "error"
        });
        break;
      case 401:
        sessionStorage.removeItem("user");
        Vue.prototype.$message({
     
          message: error.message || "密码错误或账号不存在!",
          type: "warning",
          onClose: function () {
     
            location.reload();
          }
        });
        break;
      case 403:
        Vue.prototype.$message({
     
          message: error.message || "无访问权限,请联系企业管理员",
          type: "warning"
        });
        break;
      default:
        Vue.prototype.$message({
     
          message: error.message || "服务端异常,请联系技术支持",
          type: "error"
        });
    }
  }
  return Promise.reject(error).catch(e => {
     
    e
  });
};

10.文件大小换算

//文件大小换算
export const getFileSize = function (fileByte) {
     
  var fileSizeByte = fileByte;
  var fileSizeMsg = "";
  if (fileSizeByte < 1048576)
    fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
  else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
  else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824)
    fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
  else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824)
    fileSizeMsg = "1GB";
  else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776)
    fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  else fileSizeMsg = "文件超过1TB";
  return fileSizeMsg;
};

11.下载文件

//下载文件
export const downloadfile = function (file) {
     
  let url = '';
  const index = file.file_path.indexOf("http");
  if (index == 0) {
     
    url = file.file_path
  } else {
     
    url = process.env.VUE_APP_BASIC_File + file.file_path
  }
  const filename = file.file_name
  fetch(url).then(res => res.blob().then(blob => {
     
    var a = document.createElement('a');
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  }));
};

12.图片、文件url对http的处理

//图片、文件url对http的处理
export const staticPath = (url) => {
     
  if (url) {
     
    const index = url.indexOf("http");
    if (index == 0) {
     
      return url
    } else {
     
      return process.env.VUE_APP_BASIC_File + url
    }
  } else {
     
    return ""
  }
};

13.列表转树状

//列表转树(父级为1)
export const listToTree = function (mid, ckey, oldArr) {
     
  oldArr.forEach(element => {
     
    let parentId = element[ckey];

    if (parentId != '1') {
     
      oldArr.forEach(ele => {
     
        if (ele[mid] == parentId) {
     
          if (!ele.children) {
     
            ele.children = [];
          }
          ele.children.push(element);
        }
      });
    }
  });
  oldArr = oldArr.filter(ele => {
     
    return ele[ckey] == "1"
  });
  return oldArr;
};

14.数组去重

//数组去重
export const unique = function (arr) {
     
  return arr.filter(function (item, index, arr) {
     
    return arr.indexOf(item, 0) === index
  })
}

15.数组对象去重

//数组对象去重
export const arrObjUnique = function (arr, key) {
     
  var obj = {
     };
  arr = arr.reduce(function (item, next) {
     
    obj[next[key]] ? '' : obj[next[key]] = true && item.push(next);
    return item;
  }, []);
  return arr
}

16.数组按某一属性分组

//数组按某一属性分组
export const group_signal = (list, field) => {
     
  var obj = {
     };
  for (var i = 0; i < list.length; i++) {
     
    for (const item in list[i]) {
     
      if (item == field) {
     
        obj[list[i][item]] = {
     
          list: obj[list[i][field]] ? obj[list[i][field]].list : [],
          type: list[i][field]
        };
      }
    }
    obj[list[i][field]].list.push(list[i])
  }
  var att = [];
  for (const item in obj) {
     
    att.push({
     
      list: obj[item].list,
      type: obj[item].type,
    })
  }
  return att;
};

17.html实体字符转标签

//html实体字符转标签
export const escapeHTML = (a) => {
     
  a = "" + a;
  return a.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
};

18.过滤掉html的图片和其他标签

//过滤掉html的图片和其他标签
export const filterImg = (a) => {
     
  return a.replace(/<(p|div)[^>]*>(| )<\/\1>/gi, '\n').replace(//gi, '\n').replace(/<[^>/]+>/g, '').replace(/(\n)?<\/([^>]+)>/g, '').replace(/\u00a0/g, ' ').replace(/ /g, ' ').replace(/<\/?(img)[^>]*>/gi, ' ').replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "\'").replace(/"/g, "\"").replace(/<\/?.+?>/g, "")
};

19.获取对象key并返回数组

//获取对象key 并返回数组 和 所需需要值的数组  oldname 为数组
export const getObjArr = (obj, oldname) => {
     
  var data = {
     
    key: [],
  };
  if (oldname && oldname.length > 0) {
     
    for (let i = 0; i < oldname.length; i++) {
     
      data[oldname[i]] = [];
    }
  }
  for (let key in obj) {
     
    data.key.push(key);
    if (oldname && oldname.length > 0) {
     
      var olObj = obj[key];
      for (let key1 in olObj) {
     
        if (data[key1]) {
     
          var val = olObj[key1] ? olObj[key1] : 0;
          data[key1].push(val);
        }
      }
    }
  }
  return data;
};

20. 防抖

// 防抖
export const debounce = function (fn, delay) {
     
  var delay = delay || 500;
  var timer;
  return function () {
     
    var th = this;
    var args = arguments;
    if (timer) {
     
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
     
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

20. 判断手机号

//判断手机号
export const isPhone = (pone) => {
     
  var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (!myreg.test(pone)) {
     
    return false;
  } else {
     
    return true;
  }
}

21. 判断邮箱

//判断邮箱
export const isEmail = (emailInput) => {
     
  var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
  if (!myreg.test(emailInput)) {
     
    return false;
  } else {
     
    return true;
  }
}

22. 判断是否是移动端

// 判断是否是移动端
export const isMobile = () => {
     
  let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return flag;
}
export const getHashQuery = (val) => {
     
  const w = location.hash.indexOf('?');
  const query = location.hash.substring(w + 1);

  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
     
    const pair = vars[i].split('=');
    if (pair[0] == val) {
     
      return pair[1];
    }
  }
  return (false);
}

23. 判断是微信、企业微信、钉钉

//判断是微信、企业微信、钉钉
export const platform = () => {
     
  var ua = window.navigator.userAgent.toLowerCase();
  if ((ua.match(/MicroMessenger/i) == 'micromessenger') && (ua.match(/wxwork/i) == 'wxwork')) {
     
    // alert("企业微信客户端");
    return 'workWx'
  } else if (ua.match(/micromessenger/i) == 'micromessenger') {
     
    // alert("微信客户端");
    return 'WX'
  } else if (ua.match(/DingTalk/i) == 'dingtalk') {
     
    return 'DingTalk'
  } else {
     
    alert('未匹配到')
    return
  }
}

你可能感兴趣的:(vue好用的组件,javascript,vue.js,es6,前端,封装)