Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to trigger component method from parent in VueJS?

Tags:

vue.js

I have been searching for information and have only found a way to emit events from child components which can be then listened for in parent components. Is there any way to call a child method from parent component?

like image 509
naneri Avatar asked Apr 19 '17 11:04

naneri


People also ask

How VueJS trigger child component method from parent?

Just add a "ref='someChild" to your child component and access it in your parent via "this.

How do you call a component method from parent Vue?

To call a method in a child component with Vue. js, we can pass in a prop from the parent component to its child. Then in the child component, we watch the prop's value and run the method we want. in the child component to register the testProp prop and add the sayHello method.

How do you call child method from parent in Vue 3?

To call methods in a child component from the parent, we assign a ref to the component and get its methods from there. If we want to call a method in the parent component from the child, then we emit an event in the child component and listen to that event in the parent component.


2 Answers

Yup, just find your component in children array, or grab it by ref attribute, and call method :) ref doc

lets assume that your child component has method x. According to documentation:

<div id="parent">   <user-profile ref="profile"></user-profile> </div>  var child = this.$refs.profile; child.x(); 
like image 120
donMateo Avatar answered Sep 20 '22 18:09

donMateo


I think a good pattern for this is emitting an event from the parent component and listening to it in the child component, using an Event Bus.

That would be:

in main.js

export const bus = new Vue() 

in Parent.vue:

import {bus} from 'path/to/main'  // Where you wanna call the child's method: bus.$emit('customEventName', optionalParameter) 

in Child.vue:

import {bus} from 'path/to/main'  // Add this to the mounted() method in your component options object: bus.$on('customEventName', this.methodYouWannaCall) 
like image 20
bformet Avatar answered Sep 17 '22 18:09

bformet