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>

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

  this.mensagemEdit = mensagem;

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

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

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

Leave a ReplyCancel reply