Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a new object instead of assigning a reference to the existing object in `Vue3 Option Api`

props:{
    variants:{
        type: Array,
        default: []
    }
    options:{
        type: Array,
        default: []
    },
},
data(){
    return{
        item:{
            quantity: 1,
            options: this.options,
        },
    }
},

I have a problem with this code: When i change item.options value also options get changed because as i understand, i am just assigning a reference to options.

How to create a new object for item.options instead of assigning a reference to the existing object in Vue3 Option Api.

I tried {...this.options} but it didnt work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If it’s an array of primitives, shallow cloning is enough to achieve the desired result:

item:{
    quantity: 1,
    options: [...this.options],
}

Otherwise, you will need to perform deep cloning for which there are multiple ways to achieve it, you can search for it however using JSON.parse(JSON.stringify({})) isn’t recommended.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading