vue 封装对象深拷贝方法
- 在 src/ utils文件夹下面新建
index.js
export function deepClone(obj) {
const _toString = Object.prototype.toString
if (!obj || typeof obj !== 'object') {
return obj
}
if (obj.nodeType && 'cloneNode' in obj) {
return obj.cloneNode(true)
}
if (_toString.call(obj) === '[object Date]') {
return new Date(obj.getTime())
}
if (_toString.call(obj) === '[object RegExp]') {
const flags = []
if (obj.global) { flags.push('g') }
if (obj.multiline) { flags.push('m') }
if (obj.ignoreCase) { flags.push('i') }
return new RegExp(obj.source, flags.join(''))
}
const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}
for (const key in obj) {
result[key] = deepClone(obj[key])
}
return result
}
- 使用
<script>
import { deepClone } from '@/utils/index'
export default {
name: "HomeView",
data() {
return {
obj: {
a: 1,
b: 2,
c: 3,
},
};
},
mounted(){
let newObj = deepClone(this.obj)
console.log(newObj)
newObj.c = 4
console.log(newObj)
console.log(this.obj)
}
};
</script>
- 搞定 复制可直接用!