【问题标题】:VueJS - Props are not updated in child component by changes in parentVueJS - 子组件中的道具不会因父组件的更改而更新
【发布时间】:2017-07-03 14:59:46
【问题描述】:

当我在父组件中更改道具时,道具不会更新

父组件:

我将controlData 值作为子组件道具control 的默认值,它等于2,当我第一次运行我的应用程序时,我可以看到该值

data() {
  return {
    controlData: 2
  }
}

ready() 中,我需要从后端加载数据并将该值设置为子组件道具control 等于来自后端的数据。

但是现在我只想在父组件准备好时更改control(子组件中的值)。 所以我在父组件中做了这个:

ready() {
  this.controlData = 55;
}

然后,当controlData 发生更改时,我使用 v-bind 将该值发送给子级

<child-component :control="controlData"></child-componenet>

子组件:

我的子组件中有这个

    export default Bar.extend({ 
    props: ["control"],
    ready() {
      console.log(this.control); // I see only default value "2" not "55" - but I expect to see "55" because I changed that value in ready() of parent
    }
})

我还添加了watch: {} 以查找props 的更改,但我看不到更改

watch: {
  control() {
    console.log("Control is changed"); // I don't see this message when I change controlData value in parent and then by v-bind:control="controlData" i send that data in child component
  }
}

【问题讨论】:

  • 这是 Vue 版本 1?
  • 是的,我们使用的是 VueJS 1

标签: javascript vue.js vue-component vue-chartjs


【解决方案1】:

如果正确实施,您发布的代码应该会更新子属性。

有一点需要注意,孩子的 ready() 钩子将在父 ready() 钩子之前执行。所以你应该看到控制台日志如下:

2
Control is changed

这对我使用 Vue 1.0.28 有效:

https://codepen.io/camaulay/pen/wejpPa?editors=1011

JS:

var child = Vue.extend({
  template: '<div>Child data: {{ control }}</div>',
  props: ['control'],
  ready () {
      console.log(this.control);
  },
  watch: {
    control () {
      console.log("Control is changed")
      console.log(this.control)
    }
  }
})

var app = new Vue({
  el: '#app',
  components: {
    'child': child
  },
  data () {
    return {
      controlData: 2
    }
  },
  ready () {
    this.controlData = 55
  }
})

HTML:

<div id="app">
  <child :control="controlData"></child>
  <button @click="controlData++">Increment parent data</button>
</div>

【讨论】:

  • 我用一个测试组件进行了测试,一切看起来都不错。但是没有这个,我不确定为什么,但似乎“道具”并没有真正起作用。我看到 vue-chartJS 提供了“道具”,但对我不起作用。
猜你喜欢
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2018-08-09
  • 2019-08-27
  • 2017-12-31
  • 2021-01-28
  • 2019-03-03
  • 2020-01-19
相关资源
最近更新 更多