Home > Software engineering >  How to pass a variable by prop and not allow child to change it ( vue 2 )
How to pass a variable by prop and not allow child to change it ( vue 2 )

Time:05-16

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 >{{mensagem.titulo}}</td>
  <td >
   <div >
    <a  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:

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.

CodePudding user response:

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);
  • Related