无法对ref变量的值使用structuredClone()



我想在Vue应用程序中使用structuredClone()函数。我想用它来创建一个深度克隆(而不是使用像字符串和解析或外部库这样的变通方法)。在我的设置功能中,以下代码是很好的

const a = {
foo: {
bar: "+"
}
};
const b = structuredClone(a);
console.log(b);

但我不可能在ref变量的值上使用它。此示例代码

import { ref } from "vue";
const a = ref({ foo: { bar: "+" } });
const b = structuredClone(a.value);

抛出错误

未捕获的DOMException:无法在"Window"上执行"structuredClone":无法克隆#。

引用数组中的项目也是如此

import { ref } from "vue";
const a = ref([{ foo: { bar: "+" } }]);
for (const b of a.value) {
const c = structuredClone(b);
}

如何解决这个问题?

错误表示structuredClone是在Proxy实例上执行的,无法克隆。为了实现这一点,它应该用于代理包装的原始对象:

const b = structuredClone(toRaw(a.value));

请注意,toRawa.value上使用,因为aa.value都是反应对象,而toRaw工作得很浅,需要应用于最内部的对象。

由于refreactive允许组成反应对象,toRaw可能仍然不适用于它们,因为它的工作方式:

ref({ foo: { bar: barRef } })

这将需要在使用structuredClone之前在反应对象上递归地使用toRaw。在这一点上,这并不比手动克隆对象更容易,除非使用了更奇特的对象,如SetMap等。

最新更新