Reputation: 3971
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?
Upvotes: 77
Views: 54926
Reputation: 4473
A simple way to resolve this, and stay within the recommended props/events paradigm, is to create a new prop on the child component (can be a Number), and then whenever you need to call a method in the child component, the parent component can simply increment the value of this prop, or change it however you see fit, and the child component can watch this prop for changes and call the relevant method accordingly.
I think it's a rather verbose way of doing things, and much prefer using defineExpose
to expose a method from the child component (for example a reload()
method) up to the parent, but it will satisfy the purists.
Upvotes: 1
Reputation: 14161
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)
Upvotes: 27
Reputation: 2394
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();
Upvotes: 135