/**
* 对象深拷贝工具类
* 拦截器:filter 参数[key, value, ang(fn)]
*/
export default class OUtil {
constructor(...fn) {
this.filters = fn
}
agn(source) {
// 判空
if (source == null) return null
// 判断是否对象类型
if (typeof source === 'object') {
// 是否数组
if (Array.isArray(source)) {
let result = []
for (let x in source) {
result.push(this.agn(source[x]))
}
return result
}
// 是否正则对象
if (source.constructor === RegExp) return source
// 为 map 类型
let result = {}
for (let key in source) {
for (let index in this.filters) {
// 拦截器不是一个函数
if (!(typeof this.filters[index] === 'function')) {
result[key] = this.agn(source[key])
}
// 执行拦截器
let data = this.filters[index](key, source[key], this.agn)
if (data === '$ignore$') {
continue
}
// 没有结果返回时
result[key] = (typeof data === 'undefined') ? this.agn(source[key]) : data
}
}
return result
}
// 不是对象则直接返回
else {
return source;
}
}
}
项目所用 :
src / views / preview / index.vue
<script> export default { name: 'Preview', data() { return { } }, created() { let _list = this.$store.state.saveData let newArr = [] _list.map((item) => { newArr.push(this.deepClone(item)) // 数组进行深拷贝 )} this.data = newArr }, methods: { // 对象深度克隆 deepClone(obj) { let newObj = {} if (typeof obj === 'object') { // 数组或对象 if (obj instanceof Array) { newObj = [] } for (var key in obj) { let val = obj[key] newObj[key] = typeof val === 'object' ? this.deepClone(val) : val } return newObj } else { return obj } } } } </script>