//限制最多输入2位小数
clearNoNum =(value)=>{
const reg = /^(-)*(\d+)\.(\d\d).*$/
if(value) {
value.toString().replace(reg, '$1$2.$3')
}
}
/**
* 时间戳转换成日期格式
* @param {int} date 日期時間戳
* @param {string} format 日期格式字符串.如'yyyy-MM-dd HH:ss:mm'
*/
export function formatDate(date, format) {
date = new Date(parseInt(date))
const dict = {
'yyyy': date.getFullYear(),
'M': date.getMonth() + 1,
'd': date.getDate(),
'H': date.getHours(),
'm': date.getMinutes(),
's': date.getSeconds(),
'MM': ('' + (date.getMonth() + 101)).substr(1),
'dd': ('' + (date.getDate() + 100)).substr(1),
'HH': ('' + (date.getHours() + 100)).substr(1),
'mm': ('' + (date.getMinutes() + 100)).substr(1),
'ss': ('' + (date.getSeconds() + 100)).substr(1)
}
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function () {
return dict[arguments[0]]
})
}
/**
* 从url中提取参数
* @param {*} paraName 参数名称
* @param {*} url url字符串
*/
export function getUrlParam(paraName, url) {
let arrObj = url.split('?')
if (arrObj.length > 1) {
let arrPara = arrObj[1].split('&')
let arr
for (let i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=')
if (arr != null && arr[0] === paraName) {
return arr[1]
}
}
return ''
}
else {
return ''
}
}
/**
* 将base64转为文件流
* @param base64
*/
export function convertBase64UrlToFile(base64) {
const bytes = window.atob(base64.split(',')[1])
const ab = new ArrayBuffer(bytes.length)
const ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i)
}
return new Blob([ab], { type: 'image/png' })
}
function getBase64Image(img) {
let canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
return canvas.toDataURL('image/' + ext)
}
//将url图片地址转为base64位
export function convertUrlToBase64Url(url) {
return new Promise(resolve => {
let image = new Image()
image.crossOrigin = 'anonymous'
image.src = url
image.onload = function () {
resolve(getBase64Image(image))
}
})
}
//递归压缩图片
export function compressImagesOneByOne(filePaths = [], maxSize, results = [], successUp = 0, index = 0) {
return new Promise((resolve) => {
if (filePaths.length === 0) {
resolve(results)
} else {
compressImages(filePaths[index].file, maxSize).then(res => {
results = results.concat(res)
successUp++
index++
if (index >= filePaths.length) {
console.log('压缩成功' + successUp)
if (successUp === filePaths.length) {
resolve(results)
} else {
console.log('压缩失败···')
}
} else {
compressImagesOneByOne(filePaths, maxSize, results, successUp, index).then(res => {
resolve(res)
})
}
})
}
})
}
export function compressImages(file, maxSize) {
return new Promise((resolve) => {
let imageDataReader = new FileReader()
imageDataReader.readAsDataURL(file)
imageDataReader.onload = function () {
let size = file.size
let name = file.name
let imgSrc = this.result
if (size > 1024 * 1024 * maxSize) {
let img = new Image()
img.src = imgSrc
img.onload = function () {
let that = this
let w = that.width * 0.5, h = that.height * 0.5
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
let anw = document.createAttribute('width')
anw.nodeValue = w
let anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(that, 0, 0, w, h)
let base64 = canvas.toDataURL('image/png', 0.5)
imgSrc = base64
let strLength = base64.length
let fileLength = parseInt((strLength - (strLength / 8) * 2).toString()) / (1024 * 1024)
if (fileLength > maxSize) {
compressImages(dataURLtoFile(imgSrc, name), maxSize).then(res => {
resolve(res)
})
} else {
resolve({
file: dataURLtoFile(imgSrc, name),
url: imgSrc
})
}
}
} else {
resolve({
file: file,
url: imgSrc
})
}
}
})
}
// 将base64转换为文件
export function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], filename, { type: mime })
}
/**
* 遍历对象数组,将每一项的title赋值给label
* @param {*} arr
* @returns
*/
static setObjArrayKey(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i].label = arr[i].title;
if(arr[i].hasChildren) {
this.setObjArrayKey(arr[i].children);
}
}
return arr
}
// 将2017-12-13 16:00:00转换成标准时间对象
var parserDate = function (date) {
var t = Date.parse(date);
if (!isNaN(t)) {
return new Date(Date.parse(date.replace(/-/g, "/")));
} else {
return new Date();
}
};
将时间对象转为字符串格式
// 时间格式化
function timeFormat(dt) {
return (
// spliceZero(dt.getFullYear()) + '-' + spliceZero(dt.getMonth() + 1) + '-' + spliceZero(dt.getDate())
// + " " + spliceZero(dt.getHours()) + ":" + spliceZero(dt.getMinutes()) + ":" + spliceZero(dt.getSeconds())
spliceZero(dt.getHours()) + ":" + spliceZero(dt.getMinutes())
);
}
// 时间格式化、1位数时,前面拼接0
function spliceZero(i) {
if (i.toString().length == 1) {
i = "0" + i;
}
return i;
}
按年月分组
var data = [
{"yearmonth": '2021-07', "timeItem": {date: '2021-07-23'}},
{"yearmonth": '2021-06', "timeItem": {date: '2021-06-23'}},
{"yearmonth": '2021-08', "timeItem": {date: '2021-08-21'}},
{"yearmonth": '2021-06', "timeItem": {date: '2021-06-25'}},
{"yearmonth": '2021-08', "timeItem": {date: '2021-08-23'}}
];
console.log('data');
console.log(JSON.parse(JSON.stringify(data)));
//返回所需数据格式
const mapLoction = function(arr) {
let newArr = [];
arr.forEach((item, i) => {
let index = -1;
let alreadyExists = newArr.some((newItem, j) => {
if (item.yearmonth === newItem.yearmonth) {
index = j;
return true;
}
});
if (!alreadyExists) {
newArr.push({
yearmonth: item.yearmonth,
timeItem: [item.timeItem]
});
} else {
newArr[index].timeItem.push(item.timeItem);
}
});
return newArr;
};
console.log(mapLoction(data));
树形转平级
let res = [] // 用于存储递归结果(扁平数据)
// 递归函数
const fn = source => {
source.forEach(el => {
res.push(el)
el.children && el.children.length > 0 ? fn(el.children) : '' // 子级递归
})
}
fn(this.treeData)
console.log('res')