[Vuejs]-VueJS: Updating data from method makes the properties synced

5👍

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.

Leave a comment