Call function of child from parent good practices

I was trying to call a function of the child component from a parent and am seeing several ways to do this.

Parent.vue -> ChildComponent.vue

I give it a ref

<div id="app">
  <child-component ref="childComponent"></child-component>
  <button @click="click">Click</button>  
</div>

And then used the $refs var

  this.$refs.childComponent.someFunction(2.0);

The other way i did it was using a prop and watching that prop.

props: {
  someProp: String
},
watch:{
  someProp(val){
    //do something with the value 
  }
}

What is the best way or the recommended way of doing this? And why?

1 Like

I share the opinion of Radu Dita from the following thread in SO: vue.js - Vue best practice for calling a method in a child component - Stack Overflow

I would use props in simple scenarios and Vuex, when the Child’s method has to be triggered from more than one place.

When a parent needs to call a child’s method I would simply use a ref. Using a prop and watcher to trigger a method is horribly convoluted, prone to error (what if the watcher doesn’t fire properly?), and poses no gain in terms of decoupling logic.

Yes it couples your parent to child… but that’s perfectly fine because your child can still go on as an independent component (which is the whole argument the SO answer tried to make for the prop/watcher approach). There’s zero coupling going on that isn’t anything above the same sort of coupling you’d have with a prop.