Search code examples
vue.js

Vue best practice for calling a method in a child component


I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.

To make this simple I have created a really simple version of what I would like to achieve.

I have a parent Vue, parent.vue. It has a button:

<template>
    <div>
        <button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
    </div>
</template>

In the child Vue, child.vue I have a method with a function:

methods: {
    sayHello() {

        alert('hello');
   }
  }

I would like to call the sayHello() function when I click the button in the parent.

I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.

What would be the simplest way to just execute the function in my method?

Apologies, this does seem extremely simple, but I have really tried to do some research.

Thanks!


Solution

  • 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)