平時常用的一些功能性函式
關于原生JS
16進制轉rgb()或rgba()字串
const hexToRgb = (hexT, opacity) => {
const rgb = [];
let hex = hexT.toString(16);
hex = hex.substr(1); //去除前綴 # 號
if (hex.length === 3) {
// 處理 "#abc" 成 "#aabbcc"
hex = hex.replace(/(.)/g, "$1$1");
}
hex.replace(/../g, function(color) {
rgb.push(parseInt(color, 0x10)); //按16進制將字串轉換為數字
});
const color = rgb.join(",");
return typeof opacity === "number" ? `rgba( ${color} , ${opacity} )` : `rgb( ${color} )`;
};
檔案大小單位轉換
/**
* @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];
}
}
時間轉換
/**
* 時間格式化
* @param {date} time 傳入的時間戳 | 時間
* @param {string} type 回傳的格式化時間
*/
function formatDate(timer, type = 'YMDHMS', bar = '-') {
if (!timer) return ''
let date = timer ? new Date(timer) : new Date()
let Y = date.getFullYear()
let M = zero(date.getMonth() + 1)
let D = zero(date.getDate())
let h = zero(date.getHours())
let m = zero(date.getMinutes())
let s = zero(date.getSeconds())
const TIME_NOW = {
YM: Y + bar + M,
YMD: Y + bar + M + bar + D,
YMDHMS: Y + bar + M + bar + D + ' ' + h + ':' + m + ':' + s,
HMS: h + ':' + m + ':' + s
}
return type ? TIME_NOW[type] : TIME_NOW
function zero(date) {
return date < 10 ? '0' + date : date
}
}
決議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 = https://www.cnblogs.com/gaoguowen/p/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=https://www.cnblogs.com/gaoguowen/p/"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 = https://www.cnblogs.com/gaoguowen/p/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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/79806.html
標籤:JavaScript
上一篇:JavaScript 之 作用域
下一篇:ES6中類和物件的注意問題
