【问题标题】:Unable to use structuredClone() on value of ref variable无法对 ref 变量的值使用结构化克隆()
【发布时间】:2022-06-15 22:27:30
【问题描述】:

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

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);

抛出错误

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': # could not be clone.

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

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

如何解决这个问题?

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

错误意味着structuredClone 是在Proxy 实例上执行的,而cannot be cloned。为了允许这样做,它应该用于代理包装的原始对象:

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

注意toRaw 用于a.value,因为a 和a.value 都是反应性对象,而toRaw 工作较浅,需要应用于最里面的对象。

由于ref 和reactive 允许组合反应对象,toRaw 仍然可能由于其工作原理而无法为它们工作:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 2020-05-06
    • 2017-11-07
    • 1970-01-01
    相关资源
    最近更新 更多