Reactive object nested in the reactive object. Any issues expected? #11636
-
const child = {b: 2};
const parent = reactive(
{
a: 1,
child: reactive(child)
}
) What happens if I apply a UPD: What I found so far myself is that the watcher's callback on UPD: The soultion to the latter finding is to copy or clone the watched reactive object as per below discussion. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
What you found is not related to the specific example you provided. When you watch a reactive object with You can get something like that with watch() => ({ ...parent.child}), (newChildCopy, oldChildCopy) => {
console.log(oldChildCopy) // => { b: 2 }
console.log(newChildCopy) // => { b: 3 }
parent.child === oldChildCopy // false
parent.child === newChildCopy // false
isReactive(oldChildCopy) /// false
isReactive(newChildCopy) /// false
})
parent.child.b = 3 |
Beta Was this translation helpful? Give feedback.
What you found is not related to the specific example you provided. When you watch a reactive object with
watch(parent.child, ...)
and then mutateparent.child.b
, there will not be "old" state, because you mutated the child object. for "old" state to exist, a copy ofchild
would have to be created prior to the mutatation.You can get something like that with
watch() => ({ ...parent.child}), ...)
. now Vue observes this getter function, and this getter function will create a shallow copy of the object whenever the watch is triggered. Now you will have a new and old object (but plain ones, none will be the original instance ofchild
).