VueJS Grandchild component call function in Great grandparent component

后端 未结 1 772
失恋的感觉
失恋的感觉 2021-01-03 04:12

Suppose I have a child component that want to send a message to a great grandparent, the code will be like this, correct me if I\'m wrong:

Vue.component(\'ch         


        
相关标签:
1条回答
  • 2021-01-03 04:47

    Not if you want to maintain encapsulation. greatgrandparent is not supposed to know about child. It knows about grandparent, but not that there are sub-components or how many. In principle, you can swap one implementation of grandparent out for another that doesn't have multiple layers. Or has even more layers to get to child. And you could put child into a top-level component.

    You already know about the notion of a global event bus. A bus doesn't have to be global, though. You can pass it down the props chain. (You could use greatgrandparent itself as the bus, but that would expose it to its children; better hygiene to make a real bus.)

    This distinguishes top-level components from sub-components: a sub-component will receive a bus prop to perform the functions of the top-level component that it helps to implement. A top-level component will originate the bus.

    Vue.component('child', {
      template: `<div v-on:click="clicked">Click me</div>`,
      props: ['bus'],
      methods: {
        clicked: function() {
          this.bus.$emit('clicked', 'hello');
        },
      },
    });
    
    Vue.component('parent', {
      template: `<child :bus="bus"></child>`,
      props: ['bus']
    });
    
    
    Vue.component('grandparent', {
      template: `<parent :bus="bus"></parent>`,
      props: ['bus']
    });
    
    Vue.component('greatgrandparent', {
      template: `<grandparent :bus="bus" v-on:clicked="clicked"></grandparent>`,
      data() {
        return {
          bus: new Vue()
        };
      },
      created() {
        this.bus.$on('clicked', this.clicked);
      },
      methods: {
        clicked: function(msg) {
          console.log('message from great grandchild: ' + msg);
        },
      },
    });
    
    new Vue({
      el: '#app'
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
    <greatgrandparent id="app"></greatgrandparent>

    0 讨论(0)
提交回复
热议问题