Reputation: 4280
I'm using VueJS. There is a very simple case. I have the following as data:
data: {
a: {"name":null},
b: {"name":null}
}
I am taking user input and attaching it to 'a' using v-model.
<input type="text" v-model="a.name">
Then I have a method, which when triggered, should copy the value from a to b.
save() {
this.b=this.a
}
This works fine the first time, but once I've triggered the method, both a and b are permanently synced. Why is that happening and how can I keep a and b separate unless the save method is triggered. So, after the method is triggered once, then everytime you update a, it's updating b as well which should not happen.
The bellow JS Bin shows the issue:
https://jsbin.com/kofobifego/1/edit?html,js,console,output
Upvotes: 0
Views: 46
Reputation: 795
It is because objects are reference types in JS.Try the following code.
save() {
this.b.name = this.a.name
}
Simplified explanation: When you create an object in JavaScript, a space in the memory is reserved for that object. What you assign to variable is a reference to that object - think of it as a path / link to the place in memory where an object exists. Therefore the code below...
this.b = this.a
... takes the reference that this.a holds and assigns a copy of it to the this.b. Now both this.a and this.b have a reference assigned, but it leads to the same object in memory. This is why modifying this.a also "modifies" this.b.
Please refer to this article for more detailed explanation of the topic.
Upvotes: 5