0

I've got parent component with a button

<btn @click="validate">Run child method - and validate something!</btn>
<child-component></child-component>

And I have a child component which has a method:

methods:{
   validate () {...}
}

I want to call this method from my parent component. How to do that?

Are there any pros/cons on given solution?

gileneusz
  • 1,435
  • 8
  • 30
  • 51
  • 1
    Possible duplicate of [Call a Vue JS component method from outside the component](https://stackoverflow.com/questions/33682651/call-a-vue-js-component-method-from-outside-the-component) –  Mar 02 '18 at 20:44
  • @icecream_hobbit oh, that's right, but my question is much more simpler :) – gileneusz Mar 02 '18 at 20:51
  • 1
    I would recommend passing a bus to the child as a prop, so the child can call its own methods. https://stackoverflow.com/questions/43256978/event-from-parent-to-child-component/43258428#43258428 – Roy J Mar 02 '18 at 21:23
  • @RoyJ Thanks for this suggestion. I'll look at this – gileneusz Mar 02 '18 at 22:48

1 Answers1

2

You can add the attribute ref and use the ref value to access the component/call its methods.

<child-component ref="child" ></child-component>


this.$refs.child.validate();

https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs

Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using ref. For example:

var parent = new Vue({ el: '#parent' }) // access child component instance var child = parent.$refs.profile

In your case: <btn @click="$refs.child.validate()">Run child method - and validate something!</btn>

tony19
  • 125,647
  • 18
  • 229
  • 307