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?

4
  • 1
    Possible duplicate of Call a Vue JS component method from outside the component Commented Mar 2, 2018 at 20:44
  • @icecream_hobbit oh, that's right, but my question is much more simpler :) Commented Mar 2, 2018 at 20:51
  • 1
    I would recommend passing a bus to the child as a prop, so the child can call its own methods. stackoverflow.com/questions/43256978/… Commented Mar 2, 2018 at 21:23
  • @RoyJ Thanks for this suggestion. I'll look at this Commented Mar 2, 2018 at 22:48

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.