1

I have a form that has a modal that I use to populate an array within the form. Every time the modal is submitted, I push the Vue object into an array that is on the main form. The problem I'm facing is that every item in the array is linked and when I edit one item, all the items in the array get edited.

data: {
  myForm: {
    form_element: null,
    my_array: [],
  },
  modalForm: {
    modalFormElement: null,
  },
},
methods: {
  addRow(){
    this.myForm.my_array.push(this.modalForm);
  },
},

Assigning this.modalForm to a variable first did not work.

4
  • Can you share your template code also. Commented Aug 16, 2020 at 21:13
  • this.myForm.my_array.push([...this.modalForm]) Commented Aug 16, 2020 at 22:15
  • You need to clone this.modalForm before you push it to the array so that you are not storing the same object in the array multiple times. Maybe a deep clone. Commented Aug 16, 2020 at 23:49
  • @connexo wrong brackets I think. I'd go with {...this.modalForm} Commented Aug 16, 2020 at 23:49

1 Answer 1

4

This is a reference issue. The modalForm object (i.e this.modalForm) references the same place in memory. When you push this.modalForm into the array, changing the value of a property of the object will change the rest. To prevent this issue, copy the modalForm object before pushing it to the array.

data: {
  ...
  modalForm: {
    modalFormElement: null,
  },
},
methods: {
  addRow(){ //
    this.myForm.my_array.push({...this.modalForm}); // shallow clone the object using the es2015 spread syntax
  },
},

The following are other ways to clone objects in JavaScript, but I will stick to the es2015 spread syntax in my example. For more on javascript references for objects, see this

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.