In my parent vue component I have a user
object.
If I pass that user object to a child component as a prop:
<child :user="user"></child>
and in my child component I update user.name
, it will get updated in the parent as well.
I want to edit the user object in child component without the changes being reflected in the user object that is in parent component.
Is there a better way to achieve this than cloning the object with: JSON.parse(JSON.stringify(obj))
?
You don't have to use the
JSON
object.Use
localUser
(or whatever you want to call it) inside your child.Edit
I had modified a fiddle created for another answer to this question to demonstrate the above concept and @user3743266 asked
The current component looks like this:
Because I made the design decision to use a local copy of the user, @user3743266 is correct, the component is not automatically updated. The property
user
is updated, butlocalUser
is not. In this case, if you wanted to automatically update local data whenever the property changed, you would need a watcher.Here is the updated fiddle.
This allows you full control over when/if the local data is updated or emitted. For example, you might want to check a condition before updating the local state.
As I said elsewhere, there are times when you might want to take advantage of objects properties being mutable, but there are also times like this where you might want more control.
you can have a data variable just with the information you want to be locally editable and load the value in the created method
This way you keep it clear of which data you are editing. Depending on the need, you may want to have a watcher to update the localData in case the user prop changes.
According to this, children "can't" and "shouldn't" modify the data of their parents. But here you can see that if a parent passes some reactive data as a property to a child, it's pass-by-reference and the parent sees the child's changes. This is probably what you want most of the time, no? You're only modifying the data the parent has explicitly shared. If you want the child to have an independent copy of
user
, you could maybe do this with JSON.parse(JSON.stringify()) but beware you'll be serializing Vue-injected properties. When would you do it? Remember props are reactive, so the parent could send down a new user at any time, wiping out local changes?Perhaps you need to tell us more about why you want the child to have it's own copy? What is the child going to do with its copy? If the child's user is derived from the parent user in some systematic way (uppercasing all text or something), have a look at computed properties.