我覺得JavaScript 實用函數

平時常用的一些功能性函數

關於原生JS

文件大小單位轉換

/**
 * @desc bytesToSize 字節單位換算
 * @param bytes 傳入以bit爲單位的數據
 */
const bytesToSize = function (bytes) {
    const k = 1024;
    if (!bytes || bytes === 0) return '0 B';
    if (typeof (bytes) == 'string') {
        return bytes
    } else {
        const byte = Math.abs(bytes); //正負數均變正數
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(byte) / Math.log(k));
        return (byte / Math.pow(k, i)).toFixed(2) + sizes[i];
    } 
}

解析URL後的參數並轉換爲對象

/**
 * @param {string} url
 * @returns {Object}
 */
export function parseURL(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}

生成隨機數

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}


關於Vue

增加圖片健壯性自定義指令

//檢測圖片是否存在
const imgIsExist = url =>
  new Promise(resolve => {
    var img = new Image();
    img.onload = function() {
      if (this.complete === true) {
        resolve(true);
        img = null;
      }
    };
    img.onerror = function() {
      resolve(false);
      img = null;
    };
    img.src = url;
  });

    // 用於判斷當前圖片是否能夠加載成功,可以加載成功則賦值爲img的src屬性,否則使用默認圖片
Vue.directive('realImg',    async (el, binding) {
      let imgURL = binding.value; //獲取圖片地址
      let defaultURL = el.getAttribute("default-img"); //獲取默認圖片地址
      if (!imgURL) return false;
      let exist = await imgIsExist(imgURL);
      if (exist) {
        el.setAttribute("src", imgURL);
      } else if (defaultURL) {
        el.setAttribute("src", defaultURL);
      }
    })

// 使用

 <img
   v-realImg="actual-url"
   :src="default-img"
   :default-img="default-img"
 />

關於 axios

接收二進制流文件亂碼問題。

1. 須將axios 配置中的responseType設置爲'arraybuffer',這樣就不會讓表格出現亂碼現象;
2. 如果要動態設置文件名則需要讓後臺將名字設置到響應頭中,否則將是一個亂碼的文件名;
3. 然後通過<a></a> 標籤的特性來,自動點擊下載文件;
4. 如果要兼容IE則需要利用navigator.msSaveOrOpenBlob方法;
5. 兼容Firefox 須將<a></a> 標籤添加到body中,最後再移除<a></a> 標籤

// axios config
 config = {
     responseType: 'arraybuffer'
    }

// 返回數據處理
getUserInfoExport(data).then(({data,headers}) => {
        let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 將服務端返回的文件流(二進制)excel文件轉化爲blob
        let fileName = headers.filename

        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE10+
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
          let downFile = document.createElement('a')
          downFile.style.display = 'none'
          downFile.href = objectUrl
          downFile.download = fileName // 下載後文件名
          document.body.appendChild(downFile)
          downFile.click()
          document.body.removeChild(downFile) // 下載完成移除元素
          // window.location.href = objectUrl
          window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能進行垃圾回收,因此一旦不再需要引用,就必須小心撤銷URL,釋放掉blob對象。
        }
      })

參考連接

關於 Node

獲取本機 IP 地址

const os = require('os');
const ip = showObj(os.networkInterfaces());

function showObj(obj){
/*     for (let devName in obj){
        let iface = obj[devName];
        for (let i = 0;i < iface.length;i++){
            let alias = iface[i];
            if (alias.family === 'IPv4'
                && alias.address !== '127.0.0.1'
                && !alias.internal){
                return alias.address;
            }
        }
    } */
     for (let devName in obj){
             let iface = obj[devName];
             for (let alias of iface ){
                if ( alias.family === 'IPv4'  && alias.address !== '127.0.0.1'  && !alias.internal) return alias.address;
             }
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章