4
votes

Hi everyone I just want some explanation about vue props data. So I'm passing value from parent component to child component. The thing is when parent data has data changes/update it's not updating in child component.

Vue.component('child-component', {
  template: '<div class="child">{{val}}</div>',
  props: ['testData'],
  data: function () {
    return {
        val: this.testData
    }
  }
});

But using the props name {{testdata}} it's displaying the data from parent properly

Vue.component('child-component', {
  template: '<div class="child">{{testData}}</div>',
  props: ['testData'],
  data: function () {
    return {
        val: this.testData
    }
  }
});

Thanks in advance

Fiddle link

2
You're creating a copy in val: this.testData. This is pretty much down to JS references.Phil
thanks @Phil, but does val wont update when values changesPenAndPapers
Also, what is your question?Phil
The data function is called once in the component lifetime, which means that val is set when the component is created. There is nothing that automatically updates val in your code. You likely want val to be a computed property, or just render the prop. Or you would watch testData and update val when a change occurs.Bert

2 Answers

6
votes

This is best explained with a very simple example

let a = 'foo'
let b = a
a = 'bar'

console.info('a', a)
console.info('b', b)

When you assign...

val: this.testData

you're setting the initial value of val once when the component is created. Changes to the prop will not be reflected in val in the same way that changes to a above are not reflected in b.

See https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow

0
votes

I resolve with! this.$set(this.mesas, i, event);

data() {
    return { mesas: [] }
},
components: {
    'table-item': table_l,    
},
methods: {
    deleteMesa: function(event) {
        let i = this.mesas.map(item => item.id).indexOf(event.id);
        console.log("mesa a borrare", i); 
        this.mesas.splice(i, 1);
    },
    updateMesa: function(event) {
        let i =this.mesas.map(item => item.id).indexOf(event.id);
        console.log("mesa a actualizar", i); 
        ///    With this method Vue say Warn
        //this.mesas[i]=event;  
        /// i Resolve as follow
        this.$set(this.mesas, i, event);
     },
     // Adds Useres online
     addMesa: function(me) {
         console.log(me);
         this.mesas.push(me);
     }
}