vue中,js封装方法之判断js对象类型 & 封装方法之js对象深拷贝
1、html版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/**
* 对象深拷贝
*/
function deepClone(data) {
const type = getObjType(data)
console.log(type);
let obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
//不再具有下一层次
return data
}
if (type === 'array') {
for (let i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (const key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}
/**
* 判断对象类型
*/
function getObjType(obj) {
const toString = Object.prototype.toString
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}
console.log(deepClone([1, 2]))
console.log(deepClone({ name: '对象', ids: [1, 2, 3] }))
console.log(deepClone(18))
</script>
</body>
</html>
2、vue版
1、封装方法
src\utils\util.js
/**
* 对象深拷贝
*/
export const deepClone = (data) => {
const type = getObjType(data)
let obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
//不再具有下一层次
return data
}
if (type === 'array') {
for (let i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (const key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}
export const getObjType = (obj) => {
const toString = Object.prototype.toString
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}
2、页面引入和使用
index.vue
<script>
import { deepClone } from '@src/utils/util'
// 用法1:处理单独的list列表
const tableList = ref(deepClone(FormData.value))
// 添加form表单数据
const refreshData = () => {
// 用法2
const newFormData = ref(deepClone(formDatas.value))
}
const resetFields = () => {
state['formRef'].resetFields()
}
const save = () => {
return new Promise((resolve, reject) => {
state['formRef'].validate(async (valid) => {
if (valid) {
console.log('~~~~~~~~state.form~~~~~~~~~~~~~~', state.form)
resolve({
data: deepClone(state.form), // 用法3
resetFields,
})
} else {
reject(valid)
}
})
})
}
</script>