How to call function on child component on parent events

后端 未结 9 1091
陌清茗
陌清茗 2020-11-27 09:16

Context

In Vue 2.0 the documentation and others clearly indicate that communication from parent to child happens via props.

Question

How does a p

9条回答
  •  粉色の甜心
    2020-11-27 10:13

    Did not like the event-bus approach using $on bindings in the child during create. Why? Subsequent create calls (I'm using vue-router) bind the message handler more than once--leading to multiple responses per message.

    The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.

    I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.

    Parent:

    {
       data: function() {
          msgChild: null,
       },
       methods: {
          mMessageDoIt: function() {
             this.msgChild = ['doIt'];
          }
       }   
       ...
    }
    

    Child:

    {
       props: ['msgChild'],
       watch: {
          'msgChild': function(arMsg) {
             console.log(arMsg[0]);
          }
       }
    }
    

    HTML:

    
       
    
    

提交回复
热议问题