无法在ref变量的值上使用构造克隆()
我想利用 structuredclone() vue应用。我想使用它来创建一个深度克隆(而不是使用诸如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);
引发错误
未能达到的domexception:无法在“窗口”上执行“构造克隆”:#无法克隆。
Ref数组中的项目也是如此
import { ref } from "vue";
const a = ref([{ foo: { bar: "+" } }]);
for (const b of a.value) {
const c = structuredClone(b);
}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该错误意味着
structuredclone
是在proxy
实例上执行的,无法克隆。为了允许,应该在原始对象上使用代理包装:请注意,
toraw
在a.value
上使用,因为这两个a
a 和a.Value
是反应性对象,Toraw
工作浅,需要应用于最内向的对象。由于
ref
和反应性
允许构成反应性对象,因此toraw
由于其工作方式而可能不起作用:这将需要递归地使用
Toraw
在使用structuredClone
之前,在反应性对象上。在这一点上,这并不比手动克隆对象更容易,除非正在使用set
等的更奇特的对象。The error means that
structuredClone
was executed onProxy
instance, which cannot be cloned. In order to allow this, it should be used on raw object that a proxy wraps:Notice that
toRaw
is used ona.value
because botha
anda.value
are reactive objects, andtoRaw
works shallowly and needs to be applied to the innermost object.Since
ref
andreactive
allow to compose reactive objects,toRaw
still may not work for them due to how it works:This would require to recursively use
toRaw
on reactive objects before usingstructuredClone
. At this point this doesn't make it easier than cloning the objects manually, unless more exotic objects likeSet
,Map
, etc are in use.hulkmaster
您也可以用这样的UNRE包裹源bj。
Objectiterator(UNREF(sourceObj)))
By hulkmaster https://github.com/vuejs/core/issues/5303#issuecomment-1543596383
You can also wrap the sourceObj with unref like this.
objectIterator(unref(sourceObj))