前端常用工具庫方法整理

前言

在閒餘的時間整理一份我們可能用到的前端工具庫方法。

1.獲取url地址參數
export function getQueryStringByStr(data) {
	const url = data; // 獲取url中"?"符後的字串
	const theRequest = {};
	if (url.indexOf('?') !== -1) {
		const str = url.substr(1);
		const strs = str.split('&');
		for (let i = 0; i < strs.length; i += 1) {
		theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
		}
	}
	return theRequest;
}
2.針對檢索值(搜索)統一處理空格問題
/**
 * @param {Object} props
 * @description 針對搜索值做統一處理
 */
export function convertParams(props) {
  const newParams = {};
  for (const index in props) {
    const item = props[index];
    const type = typeof item;
    if (item && type === 'string') {
       newParams[index] = item.trim();
     } if (Object.prototype.toString.call(item) === '[object Object]') {
        newParams[index] = convertParams(item)
      } else {
       newParams[index] = item;
     }
  }
  return newParams;
};
3.權限方法判斷
/**
 * @param {Array|String} target 目標數組
 * @param {Boolean} boolean 是否開啓與的關係
 * @description 判斷當前用戶是否在權限數據中
 */
export const authority = (target, boolean = false) => {
  const str = getProps('authority')  // 獲取當前角色的所有權限碼, 自定義獲取;
  if (Array.isArray(target)) {
    if (boolean) {
      return target.every(item => roles.indexOf(item) > -1)
    }
    return target.some(item => roles.indexOf(item) > -1)
  }
  return str && str.indexOf(target) > -1
}
4.菜單欄權限控制是否顯示
/**
 * 菜單欄權限顯示隱藏/現在很多架構都是自動化路由,有現成的權限配置
 * @param {Array} list 通過路由列表得到菜單列表
 * @returns {Array}
 * @description 通過用戶權限控制的菜單列表(簡易版)
 */
export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}
export const getMenuByAside = (list) => {
  let res = [];
  list.forEach(item => {
    if (!item.access || authority(item.access)) {
      let obj = {
        title: item.title,
        index: item.index,
        icon: item.icon,
        access: item.access || undefined,
      }
      if (hasChild(item)) obj.children = getMenuByAside(item.children)
      if (hasChild(item) && authority(item.access)) {
        obj.children = getMenuByAside(item.children)
      }
      res.push(obj)
    }
  })
  return res
}
5.二維數組轉換
/**
 * @param {Array} target 目標數組
 * @param {String} key 目標key值
 * @param {Boolean} boolean 是否需要數組轉換
 * @param {Object} option 匹配的對象key值,值:label/value/boolean
 * @return {Array}
 * @description 處理二維數組轉一維數組匹配相關字段值
 */
export const reduceConcat = (target, key, boolean, option) => {
  let newTarget = [];
  const { label, bool, value } = option || {};
  newTarget = target && target.map(item => {
    if (boolean) {
      return item[key] && item[key].map(opt => ({
        ...item,
        [key]: opt,
        [label]: bool ? item[label][value] : item[label]
      }))
    }
    return item[key];
  }
  ).reduce((a, b) => a.concat(b));
  return newTarget || [];
}
6. 時間類
// 轉換時間(時分秒)
/**
 * @param {Number|String} msd 轉換時間戳
 * @description 將時間戳轉換成時分秒
 */
export const parseTime = (msd) => {
  let time = (parseFloat(msd) / 1000) || 0 + '秒';
  if (time !== null && time !== '') {
    if (time > 60 && time < 60 * 60) {
      time = parseInt(time / 60.0) + "分" + parseInt((parseFloat(time / 60.0) -
        parseInt(time / 60.0)) * 60) + "秒";
    }
    else if (time >= 60 * 60 && time < 60 * 60 * 24) {
      time = parseInt(time / 3600.0) + "小時" + parseInt((parseFloat(time / 3600.0) -
        parseInt(time / 3600.0)) * 60) + "分" +
        parseInt((parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
          parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) * 60) + "秒";
    }
    else {
      time = parseInt(time) + "秒";
    }
  }
  return time;
}

or

export function dealTimeToText(value) {
  let time = Math.floor(value / 1000)
  let h = Math.floor(Math.floor(time / 60) / 60)
  let min = Math.floor(time / 60) % 60
  let s = Math.round(time % 3600 % 60)
  if (h > 0) {
    return `${h}h${min}min${s}s`
  } else if (min > 0) {
    return `${min}min${s}s`
  } else {
    return `${s}s`
  }
}
  • 秒轉時分秒
/**
 * @param {Number|String} value
 * @description 秒數轉化爲時分秒
*/
export const formatSeconds = (value) => {
  let secondTime = parseInt(value), minuteTime = 0, hourTime = 0;
  if (secondTime > 60) {
    minuteTime = parseInt(secondTime / 60);
    secondTime = parseInt(secondTime % 60);
    if (minuteTime > 60) {
      hourTime = parseInt(minuteTime / 60);
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  let result = "" + parseInt(secondTime) + "秒";
  if (minuteTime > 0) {
    result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + "小時" + result;
  }
  return result;
}
  • 計算當前年齡
/** 
 * @param {String} dateTime 接收的日期eg: 1994-03-2 || 1569404854000
 * @description 通用年齡計算公式
 * */
import moment from 'moment';
export const getAgeYear = (dateTime) => {
  let reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/
  let time = !reg.test(dateTime) ? moment(dateTime, 'YYYY-MM-DD') : dateTime;
  let regexp = time.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  if (!regexp) return '';
  let date = new Date(regexp[1], regexp[3] - 1, regexp[4]);
  if (date.getFullYear() == regexp[1] && (date.getMonth() + 1) == regexp[3]
    && date.getDate() == regexp[4]) {
    let year = new Date().getFullYear();
    return year - regexp[1];
  }
}
7.隨機生成16進制顏色值,並改變狀態
// 組件渲染後,500毫秒改變一次組件顏色
componentDidMount() {
	this.interval = setInterval(this.getRandomColor, 500);
}
getRandomColor = () => {
	this.setState({ 
		col: '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).slice(-6),
	});
}
8.背景水印簡易版
/** 
 * @param {str} 用戶需要顯示的水印信息
 * @description 背景水印
 * */
export function addWaterMarker(str) {
  const can = document.createElement('canvas');
  // const { body } = document;
  // body.appendChild(can);
  can.width = 200;
  can.height = 100;
  can.style.display = 'none';
  const cans = can.getContext('2d');
  cans.rotate(20 * Math.PI / 180);
  cans.font = '16px Microsoft JhengHei';
  cans.fillStyle = 'rgba(17, 17, 17, 0.50)';
  cans.textAlign = 'left';
  cans.textBaseline = 'Middle';
  cans.fillText(str, can.width / 3, can.height / 2);
  return `url(${can.toDataURL('image/png')})`;
}
9.常用code碼統一報錯提示
const codeMessage = {
  200: '服務器成功返回請求的數據。',
  201: '新建或修改數據成功。',
  202: '一個請求已經進入後臺排隊(異步任務)。',
  204: '刪除數據成功。',
  400: '發出的請求有錯誤,服務器沒有進行新建或修改數據的操作。',
  401: '用戶沒有權限(令牌、用戶名、密碼錯誤)。',
  403: '用戶得到授權,但是訪問是被禁止的。',
  404: '發出的請求針對的是不存在的記錄,服務器沒有進行操作。',
  406: '請求的格式不可得。',
  410: '請求的資源被永久刪除,且不會再得到的。',
  422: '當創建一個對象時,發生一個驗證錯誤。',
  500: '服務器發生錯誤,請檢查服務器。',
  502: '網關錯誤。',
  503: '服務不可用,服務器暫時過載或維護。',
  504: '網關超時。',
};
10.原生ajax下載導出
/**
 * @param {String} url 下載URL地址
 * @param {String|Number} downloadName 下載文件名稱
 * @Parma {type} 下載請求方法get||post
 * @description 導出Excel文件
 *  */
import Vue from 'vue';
import moment from 'moment';
import Cookies from "js-cookie";
const that = new Vue();

export function fileDownload(url, downloadName = moment(new Date(), 'YYYY-MM-DD') + "任務監控數據表", option) {
  const { type, status, message, messageErr, params } = option;

  let fileName = downloadName + '.xlsx';

  let request = new XMLHttpRequest();

  status ? that.$message({
    type: 'warning',
    showClose: true,
    message: message || '已點擊正在下載,請稍後...',
  }) : null;

  request.open(type || 'GET', url, true);

  request.setRequestHeader("Authorization", Cookies.get("user-token"));

  request.setRequestHeader(
    "Content-Type",
    params ? 'application/json' : "application/x-www-form-urlencoded; charset=UTF-8"
  );

  request.responseType = "blob";

  request.onload = function () {
    if (this.status === 200) {
      let blob = this.response;
      if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, fileName);
      } else {
        let downloadLink = document.createElement("a");
        let contentTypeHeader = request.getResponseHeader("Content-Type");
        downloadLink.href = window.URL.createObjectURL(
          new Blob([blob], { type: contentTypeHeader })
        );
        downloadLink.download = fileName;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        window.URL.revokeObjectURL(downloadLink.href)
      }
    } else {
      that.$message({
        type: 'error',
        showClose: true,
        message: messageErr ||'文件下載失敗...',
      });
    }
  };
  request.send(params ? JSON.stringify(params) : void null);
}
10.file文件轉碼
const toDataUrl = (blob) => {
	return new Promise(resolve => {
		let file = new FileReader();
		file.onload = event => {
			resolve(event.target.result);
			};
		file.readAsDataURL(blob);
	});
},
11. url參數加密
export const Base64 = {
  //加密
  encode(params) {
    return btoa(encodeURIComponent(params).replace(/%([0-9A-F]{2})/g,
      function toSolidBytes(match, option) {
        return String.fromCharCode('0x' + option);
      }));
  },
  //解密
  decode(params) {
    return decodeURIComponent(atob(params.replace(/\s/g, '+')).split('').map(option => '%' + ('00' + option.charCodeAt(0).toString(16)).slice(-2)).join(''));
  }
}

\s : 表示 space ,空格
+: 一個或多個
^: 開始,^\s,以空格開始 結束,\s$,以空格結束
|:或者
/g:global, 全局

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章