Vue props 数据未在子组件中更新

大家好,我只是想要一些关于 vue 道具数据的解释.所以我将值从父组件传递给子组件.问题是当父数据发生数据更改/更新时,它不会在子组件中更新.

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

但是使用道具名称 {{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
    }
  }
});

提前致谢

小提琴链接

推荐答案

最好用一个非常简单的例子来解释

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)

当你分配...

val: this.testData

您在创建组件时设置了一次 val 的初始值.对 prop 的更改不会反映在 val 中,就像上面对 a 的更改不会反映在 b 中一样.

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.

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

相关文章