简体   繁体   English

Vue-如何维护从祖父母到孙子的数据流?

[英]Vue - How to maintain a data flow from grandparent to grandchild?

Vue.component('grandchild', {
  template: '<div>grandchild - {{ data2.value }}</div>',
  props: [ 'data2' ]
});

Vue.component('child', {
    template: '<div>child - {{ data1.id }}<grandchild v-bind:data2="data2"></grandchild></div>',
  props: [ 'data1' ],
  data () {
    return {
        data2: {
        value: this.data1.id
      }
    };
  }
});

let v = new Vue({
    el: '#div',
  data: {
    data1: {
        id: 3
    }
  }
});

setInterval(function () {
    v.data1.id++;
}, 1000);

v passes 'data1' to child via props, v通过道具将“ data1”传递给孩子,

child passes 'data2' to grandchild via props, data2.value = data1.id 子代通过道具data2.value = data1.id将“ data2”传递给孙子代

See the setInterval function, it increases data1.id every second 参见setInterval函数,它每秒增加data1.id

But only child's dom updates 但是只有孩子的dom更新

jsFiddle: https://jsfiddle.net/xfgzwjef/1/ jsFiddle: https ://jsfiddle.net/xfgzwjef/1/

Someone can help? 有人可以帮忙吗?

The data as calculated from the initial value of the prop in the child component isn't actually being updated, as there's nothing changing it. 从子组件中的prop的初始值计算出的数据实际上并没有更新,因为没有任何更改。 It's disassociated from the prop upon creation. 在创建时就与道具分离了。

What you want is for data2 to be computed, so it actually depends on the prop passed initially. 您想要的是要计算的data2 ,因此它实际上取决于最初传递的prop。

computed: {
  data2() {
    return {value: this.data1.id}
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM