Vue best practice for calling a method in a child component

I am not sure is this the best way. But I can explain what I can do... Codesandbox Demo : https://codesandbox.io/s/q4xn40935w

From parent component, send a prop data lets say msg. Have a button at parent whenever click the button toggle msg true/false

<template>
  <div class="parent">
    Button from Parent : 
    <button @click="msg = !msg">Say Hello</button><br/>
    <child :msg="msg"/>
  </div>
</template>

<script>
import child from "@/components/child";

export default {
  name: "parent",
  components: { child },
  data: () => ({
    msg: false
  })
};
</script>

In child component watch prop data msg. Whenever msg changes trigger a method.

 <template>
  <div class="child">I am Child Component</div>
</template>

<script>
export default {
  name: "child",
  props: ["msg"],
  watch: {
    msg() {
      this.sayHello();
    }
  },
  methods: {
    sayHello() {
      alert("hello");
    }
  }
};
</script>

I don't like the look of using props as triggers, but using ref also seems as an anti-pattern and is generally not recommended.

Another approach might be: You can use events to expose an interface of methods to call on the child component this way you get the best of both worlds while keeping your code somehow clean. Just emit them at the mounting stage and use them when pleased. I stored it in the $options part in the below code, but you can do as pleased.

Child component

<template>
  <div>
    <p>I was called {{ count }} times.</p>
  </div>
</template>
<script>
  export default {
    mounted() {
      // Emits on mount
      this.emitInterface();
    },
    data() {
      return {
        count: 0
      }
    },
    methods: {

      addCount() {
        this.count++;
      },

      notCallable() {
        this.count--;
      },

      /**
       * Emitting an interface with callable methods from outside
       */
      emitInterface() {
        this.$emit("interface", {
          addCount: () => this.addCount()
        });
      }

    }
  }
</script>

Parent component

<template>
  <div>
    <button v-on:click="addCount">Add count to child</button>
    <child-component @interface="getChildInterface"></child-component>
  </div>
</template>
<script>
  export default {
    // Add a default
    childInterface: {
      addCount: () => {}
    },

    methods: {
      // Setting the interface when emitted from child
      getChildInterface(childInterface) {
        this.$options.childInterface = childInterface;
      },

      // Add count through the interface
      addCount() {
        this.$options.childInterface.addCount();
      }
    }
  }
</script>

One easy way is to do this:

<!-- parent.vue -->
<template>
    <button @click="$refs.myChild.sayHello()">Click me</button>
    <child-component ref="myChild" />
</template>

Simply create a ref for the child component, and you will be able to call the methods, and access all the data it has.


You can create a ref and access the methods, but this is not recommended. You shouldn't rely on the internal structure of a component. The reason for this is that you'll tightly couple your components and one of the main reasons to create components is to loosely couple them.

You should rely on the contract (interface in some frameworks/languages) to achieve this. The contract in Vue relies on the fact that parents communicate with children via props and children communicate with parents via events.

There are also at least 2 other methods to communicate when you want to communicate between components that aren't parent/child:

  • the event bus
  • vuex

I'll describe now how to use a prop:

  1. Define it on your child component

    props: ['testProp'],
    methods: {
      sayHello() {
        alert('hello');
      }
    }
    
  2. Define a trigger data on the parent component

    data () {
     return {
       trigger: 0
     }
    }
    
  3. Use the prop on the parent component

    <template>
     <div>
        <childComponent :testProp="trigger"/>
      </div>
    </template>
    
  4. Watch testProp in the child component and call sayHello

    watch: { 
        testProp: function(newVal, oldVal) {
          this.sayHello()
        }
    }
    
  5. Update trigger from the parent component. Make sure that you always change the value of trigger, otherwise the watch won't fire. One way of doing this is to increment trigger, or toggle it from a truthy value to a falsy one (this.trigger = !this.trigger)

Tags:

Vue.Js