如何制作 Proxy 对象的结构化克隆?

问题描述 投票:0回答:1

我正在使用 Vue3,其中很多对象都是用于反应性的代理对象。我想创建一个代理对象和最近发现的 StructuredClone 的深层副本。

https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

当我运行以下代码时,在 proxyObj 上执行结构化克隆时出错:

const obj = {
    name: "Steve",
    age: 50
}
const handler = {}
const proxyObj = new Proxy(obj, {})

console.log(proxyObj)

const objCopy = structuredClone(obj)

console.log(objCopy)

const proxyObjCopy = structuredClone(proxyObj)
console.log(objCopy)

未捕获的 DOMException:无法在“窗口”上执行“structuralClone”:# 无法克隆。

有没有办法克隆代理对象?有没有办法我可以先取消引用它,复制它,而不失去反应性?如有任何帮助,我们将不胜感激!

javascript node.js vue.js browser
1个回答
0
投票

按照您的示例,您可以使用

Object.create
Object.getOwnPropertyDescriptors

创建自己的函数
function cloneProxy(obj) {
    //creates a new object that inherits from the prototype of the original object
    const clone = Object.create(Object.getPrototypeOf(obj));
    const properties = Object.getOwnPropertyDescriptors(obj);
    
    for (prop in properties) {
        if (properties[prop].hasOwnProperty("value")) {
            clone[prop] = properties[prop].value;
        } else {
            clone[prop] = properties[prop];
        }
    }
    
    return clone;
}

const obj = {
    name: "Steve",
    age: 50
}
const handler = {}
const proxyObj = new Proxy(obj, {})
console.log(proxyObj) //{ name: 'Steve', age: 50 }

const objCopy = structuredClone(obj)
console.log(objCopy) //{ name: 'Steve', age: 50 }

const proxyObjCopy = cloneProxy(proxyObj)
console.log(proxyObjCopy) // { name: 'Steve', age: 50 }

有关这些功能的更多信息:

Object.create
--> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Object.getOwnPropertyDescriptors
--> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors

© www.soinside.com 2019 - 2024. All rights reserved.