Vue props data not updating in child component

…衆ロ難τιáo~ 提交于 2019-12-07 12:12:26

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/49419314/vue-props-data-not-updating-in-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!