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?
Just add a "ref='someChild" to your child component and access it in your parent via "this.
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.
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.
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();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With