Maninder Singh
Maninder Singh

Reputation: 133

why prop value is changing with data changes in vuejs3?

props that I'm getting

props : {
     images : Object,
     locale : String,
},

data method

data() {
        return {
            form : this.$inertia.form({
                product_images : this.images.data,
            }),
        }
    },

I'm updating project_images on click event like so

Add() {
       this.form.product_images.push({image : null});
},

but here problem is that as project_images updated with a new object. it also updates the prop images(Add the object in the data field of images props like product_images). i don't want that prop should be changed because I'm using the old prop value. why is this strange thing happening?

Upvotes: 0

Views: 124

Answers (1)

tony19
tony19

Reputation: 138276

JavaScript arrays are copied by reference, so form.product_images and images.data are referring to the same array in memory. Editing one variable would affect the other.

The solution is to deep copy the original array into a new array. One way to do that is to map the array into newly spread objects:

data() {
  return {
    form : this.$inertia.form({
      product_images : this.images.data.map(x => ({...x})),
    }),
  }
},

Upvotes: 1

Related Questions