平时常用的一些功能性函数
关于原生JS
文件大小单位转换
/**
* @desc bytesToSize 字节单位换算
* @param bytes 传入以bit为单位的数据
*/constbytesToSize =function(bytes){constk =1024;if(!bytes || bytes ===0)return'0 B';if(typeof(bytes) =='string') {returnbytes }else{constbyte =Math.abs(bytes);//正负数均变正数constsizes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];consti =Math.floor(Math.log(byte) /Math.log(k));return(byte /Math.pow(k, i)).toFixed(2) + sizes[i]; } }
解析URL后的参数并转换为对象
/**
* @param {string} url
* @returns {Object}
*/exportfunctionparseURL(url){constsearch = url.split("?")[1];if(!search) {return{}; }returnJSON.parse('{"'+decodeURIComponent(search) .replace(/"/g,'\\"') .replace(/&/g,'","') .replace(/=/g,'":"') .replace(/\+/g," ") +'"}');}
生成随机数
/**
* @returns {string}
*/exportfunctioncreateUniqueString(){consttimestamp = +newDate() +"";constrandomNum =parseInt((1+Math.random()) *65536) +"";return(+(randomNum + timestamp)).toString(32);}
关于Vue
增加图片健壮性自定义指令
//检测图片是否存在constimgIsExist =url=>newPromise(resolve=>{varimg =newImage(); 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) {letimgURL = binding.value;//获取图片地址letdefaultURL = el.getAttribute("default-img");//获取默认图片地址if(!imgURL)returnfalse;letexist =awaitimgIsExist(imgURL);if(exist) { el.setAttribute("src", imgURL); }elseif(defaultURL) { el.setAttribute("src", defaultURL); } })// 使用
关于 axios
接收二进制流文件乱码问题。
1. 须将axios 配置中的responseType设置为'arraybuffer',这样就不会让表格出现乱码现象;
2. 如果要动态设置文件名则需要让后台将名字设置到响应头中,否则将是一个乱码的文件名;
3. 然后通过<a></a> 标签的特性来,自动点击下载文件;
4. 如果要兼容IE则需要利用navigator.msSaveOrOpenBlob方法;
5. 兼容Firefox 须将<a></a> 标签添加到body中,最后再移除<a></a> 标签
// axios configconfig = {responseType:'arraybuffer'}// 返回数据处理getUserInfoExport(data).then(({data,headers}) =>{letblob =newBlob([data], {type:'application/vnd.ms-excel'})// 将服务端返回的文件流(二进制)excel文件转化为blobletfileName = headers.filenameif(window.navigator &&window.navigator.msSaveOrOpenBlob) {// IE10+window.navigator.msSaveOrOpenBlob(blob, fileName) }else{letobjectUrl = (window.URL ||window.webkitURL).createObjectURL(blob)letdownFile =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 = objectUrlwindow.URL.revokeObjectURL(objectUrl)// 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。} })
关于 Node
获取本机 IP 地址
constos =require('os');constip = showObj(os.networkInterfaces());functionshowObj(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(letdevNameinobj){letiface = obj[devName];for(letaliasofiface ){if( alias.family ==='IPv4'&& alias.address !=='127.0.0.1'&& !alias.internal)returnalias.address; } }}
也欢迎大家进群一起学习:1079817099
网友评论