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>  

And then used the $refs var


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

props: {
  someProp: String
    //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.

hi, what if the child is conditional rendered component, so ref is not an option. how do you handle it?

If it’s conditionally rendered and that condition is false then why would you be trying to call a method on the child? So the answer is in the question itself, you check to see if the child’s condition is true and that the ref exists and only then would you call the function.