/**
* 下载文件(url资源)
*/
export const downLoadUrl = (url, name, ext?) => {
try {
let link = document.createElement('a');
link.download = `${name}${ext && `.${ext}`}`;
link.href = url;
link.click();
} catch (error) {}
};
/**
* 下载文件(数据流)(把数据流转成文件下载)
*/
export const downLoadFile = (data, name, ext?) => {
try {
let content = Object.assign(data);
let link = document.createElement('a');
link.download = `${name}${ext && `.${ext}`}`;
// 字符内容转变成blob地址
let blob = new Blob([content]);
link.href = URL.createObjectURL(blob);
link.click();
} catch (error) {}
};
/**
* 生成唯一guid
*/
export const guid = () => {
var d = new Date().getTime();
var _guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (
c
) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
return `kmap-${_guid}`;
};
/**
* 数据深拷贝(暂不能拷贝函数)
*/
export const deep = (data) => {
try {
if (typeof data === 'object') {
return Object.assign(JSON.parse(JSON.stringify(data)));
} else {
return JSON.parse(JSON.stringify(data));
}
} catch (error) {
return data;
}
};
/**
* 对象深拷贝(暂不能拷贝函数)
* @param {*} obj
*/
export const copy = (obj) => {
try {
let newObj = obj.constructor === Array ? [] : {};
if (typeof obj !== 'object') {
return;
}
for (let i in obj) {
newObj[i] = typeof obj[i] === 'object' ? copy(obj[i]) : obj[i];
}
return newObj;
} catch (error) {
return obj;
}
};
/**
* 对象深拷贝(b的值复制给a,但是继承的属性不会被拷贝)
*
* @returns
*/
export const extend = (a, b) => {
try {
for (let key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
} catch (error) {
return a;
}
};
/**
* 数组去重
*
* @private
* @memberof EditModal
*/
export const unique = (arr) => {
try {
let arr1 = [];
for (let i = 0, len = arr.length; i < len; i++) {
if (!arr1.includes(arr[i])) {
// 检索arr1中是否含有arr中的值
arr1.push(arr[i]);
}
}
return arr1;
} catch (error) {
return arr;
}
};
/**
* 获取base64图片
*
* @returns
*/
export const getBase64 = (file) => {
try {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
} catch (error) {}
};
/**
* 文件转成为字符串对象
*
* @returns
*/
export const fileString = (file) => {
try {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => resolve(reader.result);
前端通用方法util.js
于 2021-04-21 11:36:37 首次发布
本文介绍了一款前端开发中常用的工具函数库util.js,它包含了一系列实用的通用方法,如类型检查、对象操作、数组处理等,极大地提高了开发效率。通过引入和使用这些函数,开发者可以更便捷地解决日常开发中遇到的问题。
摘要由CSDN通过智能技术生成