PenAndPapers
PenAndPapers

Reputation: 2108

Vue props data not updating in child component

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

Upvotes: 6

Views: 11476

Answers (2)

Phil
Phil

Reputation: 164970

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://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow

Upvotes: 7

luigivirgo
luigivirgo

Reputation: 1

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

Upvotes: 0

Related Questions