Vue: Pushing object in array from defined variable adds them by reference, and they can't be modified without affecting the variable.

Created on 4 Dec 2017  ·  5Comments  ·  Source: vuejs/vue

Version

2.5.9

Reproduction link

https://jsfiddle.net/arwany/uyndonrp/

Steps to reproduce

After the page loads, the array "persons" will be loaded with one item (Thomas).

Now I have provided two buttons to demonstrate the issue/bug I am having:

  • " Add - OK": this button pushes new object to the array by passing the object in clear js object format.
  • " Add - NOT OK": this button pushes new object to the array by passing an already defined object above (newPerson).

If you click the "Add NOT OK" button two times, and try to change the value of the array in the gray boxes, you will notice that both the object newPerson and the array objects are being changed, as if vue has added them by reference instead of adding them by value (is it even possible?).

What is expected?

To copy the newPerson variable into the array and leave it alone.

Also, when adding multiple objects, I expect to be seperated from each other, but now they seem to be changed all at the same time.

What is actually happening?

I suspect that pushing the object into the array is being added by reference instead of being added by value.


Is this an issue/feature with Javascript or with vue itself?

Most helpful comment

It should be working as expected. You should clone it by your self.

this.persons.push(Object.assign({}, this.newPerson));

or

this.persons.push({...this.newPerson});

All 5 comments

It should be working as expected. You should clone it by your self.

this.persons.push(Object.assign({}, this.newPerson));

or

this.persons.push({...this.newPerson});

This is how javascript works, you have to clone the object as @JounQin said

I am facing the same problem but using assign function, so it should be a copy.
I use a object loaded as JSON as template for new data.
When I click add it uses the JSON loaded data for assign then push it to the list of item.
The item has a subitem (v-for inside v-for).
The subitem add/remove are facing this issue. It seems that the added subitem are just a reference, so editing one changes the value also of the others. This does not afflict the data which is present at the beginning, which has not being added with the method.
I underline that I am using assign to make a copy and push it

@JounQin hi it worked for can u explain it in details please

@ua3167 It's just how JavaScript works...
They are sharing a same reference.

Was this page helpful?
0 / 5 - 0 ratings