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

32 javascript vue.js

我想在我的 Vue 应用程序中使用StructuredClone()函数。我想用它来创建深度克隆(而不是使用字符串化和解析或外部库等解决方法)。在我的设置函数中,以下代码很好

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

console.log(b);
Run Code Online (Sandbox Code Playgroud)

但我不可能将它用于 ref 变量的值。这个示例代码

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

抛出错误

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

对于 ref 数组中的项目也是如此

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

如何解决这个问题?

Est*_*ask 44

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

const b = structuredClone(toRaw(a.value));
Run Code Online (Sandbox Code Playgroud)

请注意,toRaw使用 on 是a.value因为aa.value都是响应式对象,并且toRaw作用较浅,需要应用于最里面的对象。

由于refreactive允许组合反应式对象,toRaw但由于其工作原理,仍然可能不适用于它们:

ref({ foo: { bar: barRef } })
Run Code Online (Sandbox Code Playgroud)

这需要toRaw在使用之前递归地使用反应对象structuredClone。此时,这并不比手动克隆对象更容易,除非正在使用更奇特的对象Set,如 、 等。Map