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

Vue V-Model changes multiple Objects

When i use the mounted function in vue to assign two different objects in the data area and bind one of them to a form i get a weird problem: Both Objects changes with the input of values in the form

Example:

<template>
    <v-card>
        <v-form>

        <v-text-field
        v-model="newProduct.name"
        ></v-text-field>

        <v-text-field
        v-model="newProduct.price.net"
        ></v-text-field>

        </v-form>
    </v-card>
  
</template>

<script>
export default {
    data() {
        return {
            originalProduct: {}
            newProduct:{}
        }            
    },
    mounted () {
        const productFromApi = {
            name: 'test'
            price: {
                net:20
            }
        }
        this.originalProduct = productFromApi
        this.newProduct = productFromApi
    }
}
</script>

In this example the originalProduct changes also when form is edited

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

When I assign the objects with Object.assign just the inline object price changes with the binded object newProduct

I don’t want, that the originalProduct is changed

Does anyone have a solution for this?

>Solution :

You need to make a deep copy of the object if you want to completely isolate the changes:

this.newProduct = JSON.parse(JSON.stringify(productFromApi))
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