Vue props data not updating in child component

2019-02-27 11:19发布

问题:

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