1

i'm quite new in the Vue world and i'm a bit confused about the two way data binding usage. This is my situation:
I've got a view which imports a <Modal> component. I'm passing to that component a prop, called documentData, so <Modal :documentData="document">
document is an object containing some infos, like "title", "description".

Into the Modal component i'm receiving documentData as a prop, and that's perfectly fine.

The modal is an "edit" one, so it shows 2 text fields with v-model directive and it's working perfectly fine too.

My problem occures when a user, after changing the Modal "title" field from 'Hello' to 'Hello123' clicks on "Cancel" button. Model remains "updated" and correctly does not reset.

So i tried to use watch to assign my input prop into a local data value, doing that:

watch: {
    is_show: function (newShow) {
        if(newShow){
            this.localDocumentData = this.documentData
        }
    },
}

So when "is_show" becomes true (Modal opening) i'm gonna save my documentData prop into a localDocumentData data.
Then i use localDocumentData into v-model directives like that:

<v-text-field
    v-model="localDocumentData.title"
    label="Titolo"
    outlined
    required
    dense
    :rules="[rules.required]"
></v-text-field>

That causes the model to updated too, and i can't understand why..
Is there a correct way to handle this? Basically i just want to say to my Modal component: Ok get the prop value, use it locally, but do not update the original prop because a user can always click "Cancel" and close the edit modal.

Thank you so much!!

1 Answers1

0

Objects in JavaScript are references values, you can't simply just copy using the =. This is a quick and dirty way of deep cloning an object. this.localDocumentData = JSON.parse(JSON.stringify(this.documentData))

Vitaliy Rayets
  • 2,299
  • 1
  • 6
  • 12