0

Why changes take affect on also props when I set v-model equal to props in mount hook.

export default{
  props: {
    initial_value: Array,
  },

  data(){
     return { component_value: [] }
  },

   mounted(){
     this.component_value = this.initial_value;
   }
}

So when I make some changes to component_value it also take affect on initial_value.

I wanted to write whole my code here but just tried make it short.

Ozal Zarbaliyev
  • 566
  • 6
  • 22

3 Answers3

1

Simplest way to do that is to clone your initial_value.

You can do that like this:

mounted() {
     this.component_value = JSON.parse(JSON.stringify(this.initial_value));
   }

This should work.

You can check more answers here.

mare96
  • 3,749
  • 1
  • 16
  • 28
1

Change you code in mount hook, like this below

mounted() {
   this.component_value = JSON.parse(JSON.stringify(this.initial_value));
}

It will the value of this.initial_value variable not by just reference but by data of it. In JavaScript, a variable may store two types of data: primitive and reference. And this.initial_value has reference data since it's type is an array. For more explanation please read this article source

Qonvex620
  • 3,819
  • 1
  • 8
  • 15
0
export default{
  props: ['initial_value'],

  data(){
     return { component_value: this.initial_value }
  }

}

This should work.

EDIT:

If you are going to change the props continuisly (reactivity), you must use a computed property, like this

computed: { 
      component_value(){ 
           return JSON.parse(JSON.stringify(this.initial_value) 
          } 
   }

Regards

Ignacio
  • 116
  • 4