1、过滤表单中key不存在的字段
formFilter(values, filterValue = true) {
if(Object.prototype.toString.call(values) !== '[object Object]') {
return {}
}
Object.keys(values).map(item => {
if(!item) {
delete values[item]
return
}
if(filterValue && (values[item] === undefined || values[item] === null) ) {
delete values[item]
}
})
return values
},
2、表单回显填充数据
formSetData(formData, newData) {
Object.keys(formData).map(item => {
if(newData[item] != undefined) {
formData[item] = newData[item]
}
})
},
3、判定数据类型
getDataType(object) {
if (typeof object === 'undefined') {
return 'undefined'
}
let map = {
'[object Number]': 'number',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Object]': 'object',
'[object Array]': 'array',
'[object RegExp]': 'regExp',
'[object Function]': 'function',
'[object Promise]': 'promise',
'[object GeneratorFunction]': 'generatorFunction',
'[object Null]': 'null',
}
let typeString = ''
if (object instanceof Element) {
typeString = 'element'
} else {
typeString = map[Object.prototype.toString.call(object)]
}
return typeString
},
4、深拷贝
//深拷贝
deepCopy(obj) {
// Hash表 记录所有的对象引用关系
let map = new WeakMap()
function dp(obj) {
let result = null
let keys = null,
key = null,
temp = null,
existObj = null
existObj = map.get(obj)
// 如果这个对象已被记录则直接返回
if (existObj) {
return existObj
}
keys = Object.keys(obj)
result = {}
// 记录当前对象
map.set(obj,result)
for (let i = 0
key = keys[i]
temp = obj[key]
// 如果字段的值也是一个对象则递归复制
if (temp && (Object.prototype.toString.call(temp) === '[object Array]' || Object.prototype.toString.call(temp) === '[object Object]')) {
result[key] = dp(temp)
} else {
// 否则直接赋值给新对象
result[key] = temp
}
}
return result
}
return dp(obj)
},
/**
* 深度克隆对象,不支持对象内方法的克隆
* @param {Objectany} source 待拷贝对象
* @returns {Object}
*/
deepClone(source) {
return JSON.parse(JSON.stringify(source))
},
5、格式化时间
timeFormat: (time, format) => {
let [year, month, day, hour, minutes, seconds] = [
time.getFullYear(),
(time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1),
time.getDate() >= 10 ? time.getDate() : '0' + time.getDate(),
time.getHours() >= 10 ? time.getHours() : '0' + time.getHours(),
time.getMinutes() >= 10 ? time.getMinutes() : '0' + time.getMinutes(),
time.getSeconds() >= 10 ? time.getSeconds() : '0' + time.getSeconds()
]
switch (format) {
case 'Y-M-D':
return `${year}-${month}-${day}`
case 'Y.M.D':
return `${year}.${month}.${day}`
case '年-月-日 H:M:S':
return `${parseInt(year, 10)}${temp.$t('Year')}${parseInt(month, 10)}${temp.$t('Month')}${parseInt(day, 10)}${temp.$t('day')} ${hour}:${minutes}:${seconds}`
case `年-月-日`:
return `${parseInt(year, 10)}${temp.$t('Year')}${parseInt(month, 10)}${temp.$t('Month')}${parseInt(day, 10)}${temp.$t('day')}`
case 'H:M:S':
return hour + ':' + minutes + ':' + seconds
default:
return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
}
},