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 pass a variable by prop and not allow child to change it ( vue 2 )

I’m passing a prop to a child component, and coping the prop value to a data() variable. The problem is that when I change the values of data() variable, the values on parent change to, and I dont know why.

So I have a v-for on parent where I call the editar() method

<tr v-for="(mensagem,key) in  allMensagens" :key="key">
  <td class="tipo-mensagem-td">{{mensagem.titulo}}</td>
  <td class="text-center botoes">
   <div class="grupo-botoes">
    <a class="bi bi-pencil-square" role="button" v-on:click="editar(mensagem)" title="Editar Mensagem"></a>
   </div>
  </td>
 </tr>

Then on editar I have this, where the mensagemEdit is a data() variable on parent component:

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

editar(mensagem)
{
  this.mensagemEdit = mensagem;
  this.toggleCriarMensagem("edit"); 
}

Then to show the form to edit I have something like this

 <template v-if="criarMensagem">
   <keep-alive>
     <FormAddEditMensagem :mensagemEdit="mensagemEdit" :tipoMensagem="'E'" :acao="acao"/>
   </keep-alive>
 </template>

Where I send the mensagemEdit to child, and then on it I have this line of code, where the mensagem is a data() var on child:

activated() {
    this.mensagem = this.mensagemEdit;
},

The problem its that, when I edit the values on this.mensagem, the mensagemEdit from parent assume that values, and the mensagem from v-for, takes that values, so if I close the form, changing the value of criarMensagem to false, I get the not saved, but edited values on table and I dont want that.

>Solution :

You can clone the prop value, with these methods:

  1. If the value is a simple data type (string, boolean, number):
this.mensagem = JSON.parse(JSON.stringify(this.mensagemEdit));
  1. If the value is a simple object:
this.mensagem = Object.assign({}, this.mensagemEdit);
  1. For more complex values (array of objects, nested objects) I suggest using lodash:
import { cloneDeep } from "lodash"

this.mensagem = cloneDeep(this.mensagemEdit);
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