svoruganti
svoruganti

Reputation: 672

how to initialize state with props without modifying props in vue 3

I initialize state in my vue 3 component as follows:

data() {
    return {
        new_listing: this.listing //which is a prop
    }
}

However when I bind it to an input for example:

<input type="text" placeholder="title" v-model="new_listing.title" />

the expected result is for only new_listing.title to change, however the prop listing also seems to change. How do I make it so that only the state new_listing.title changes and not the prop listing.title.

Upvotes: 0

Views: 1159

Answers (1)

Patrick
Patrick

Reputation: 1838

You need to clone the object (make a new copy).

In javascript when assigning an object to a variable it doesn't create a new copy of that object. Instead it assigns it by referencing the original object.

Therefore from the code in your question, doing { new_listing: this.listing } assigns a reference of the this.listing object to new_listing. Meaning that modifying new_listing would also modify this.listing:

To clone the object in ES6+ you can do the following. The ... is a spread syntax. In this case it's a way to clone an object.

data() {
    return {
        new_listing: {...this.listing} //which is a prop
    }
}

If you're not using ES6 check out What is the most efficient way to deep clone an object in JavaScript? to see how to clone an object.

Note: If the object contains objects (e.g. {a: {b: "h"}} then you will need to do a deep clone (clone objects within the objects).

Upvotes: 3

Related Questions