How to call function on child component on parent events
Here's a quick solution to the query: assign a ref to the child component and use this ref to call its methods directly from the parent.
The child component may look something like this:
The Parent can now call the Child's childMethod()
every time the button is clicked. Now, the child is always listening!🔊
Deep dive into vue refs
While it is tempting to stop at this point, remember: knowledge grows smarter when shared. Let's explore some of the variations you can utilise in vue refs
to run child functions from a parent component.
Accessing component methods using $refs
In Vue 2 or Vue 3 when using the Options API, this.$refs
is your best friend for calling child component methods. Just make sure the ref
attribute is assigned.
Reactive props to trigger child functions
Props being observed by child components can create opportunities to trigger its methods. Once the parent updates a prop value, a watcher in child breaks out a function.
And here's how the Child would react:
resolve communication with event bus
An event bus while now deprecated, shows how Vue has been there done that in offering solutions for parent-child component communication.
Public methods exposed by defineExpose
Here comes a hit from Vue 3's Composition API. Expose public methods with defineExpose
.
Communication using $emit and $on
Vue's event system is quite a party. It allows child components to emit events while leaving their parents to choose whether to react or not. It's like paternal instincts on an electrical circuit, if you will.
Communication patterns
Explore ways that amplify your communication between parent and child components without creating a messy echo(room).
Central state management with Vuex
For complex situations, especially in large applications, Vuex walks in like a superhero and offers centralized state management.
Flexibility with component slots
Components can be quite accommodating with their slots. They might give you more legroom compared to calling methods on child components directly.
Reactive props magic
The real magic happens when you reactively embrace props in declarative style of programming.
Was this article helpful?