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

vue.js

vue.js Problem Overview


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?

vue.js Solutions


Solution 1 - vue.js

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();

Solution 2 - vue.js

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)

Solution 3 - vue.js

Here is a simple one

this.$children[indexOfComponent].childsMethodName();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnaneriView Question on Stackoverflow
Solution 1 - vue.jsdonMateoView Answer on Stackoverflow
Solution 2 - vue.jsbformetView Answer on Stackoverflow
Solution 3 - vue.jsPratik KhadtaleView Answer on Stackoverflow