Home  >  Q&A  >  body text

Vue.js still updates props even though i is a method variable

I have the following method to compare two arrays, one from props and the other from my component. I insert every element that exists in the props array but not in my component array into a third array and add a property called "destroy: true" so I can send it to the backend Delete from database.

However, for some reason my props are updated instead of the variables I use in the method. I'm not quite sure why this is happening since I'm not referencing the prop directly, but I do copy its contents into a variable within the method.

updateArray(){
        let updatedArray = []
        let oldArray = [...this.props.array]
        oldArray.forEach(element => {
          if(this.componentArray.indexOf(element) > -1){
            updatedArray.push(element)
          }else{
            let newElement = element
            newElement.destroy = true
            updatedArray.push(newElement)
          }
        })
       return updatedArray 
},

Why does this happen? The other elements in my component work fine, only this one has issues.

P粉432930081P粉432930081399 days ago654

reply all(1)I'll reply

  • P粉465675962

    P粉4656759622023-09-16 11:40:37

    Yes, you are copying the elements of the this.props.array array into a new method local array, but since the elements of the array are objects, you end up with both The arrays all contain the same object (a reference to the object )

    You can use the spread operator let newElement = { ...element }Create a shallow copy of the original element - this will create a completely new object and copy the original All properties. But be aware that if any properties of the original object contain arrays/objects, you will face the same problem...just a little deeper

    reply
    0
  • Cancelreply