/    Sign up×
Articles /Pin to ProfileBookmark

How to call a parent method from a child component in Vue 3

Sometimes you ask yourself a question how to do something in Vue which seems to be quite simple. How do I call a parent method from a child component in Vue 3?

This seems quite simple but when you query this question in a search engine you get several different answers. Also the Vuejs events documentation is not quite clear, especially with all the different API setups nowadays (Options API, Composition API, <script setup> vs setup()).

Vue’s $emit method

It took me more time than I wished, but this is my most simple code snippet with <script setup> and the Composition API style how to call a parent method from a child component with emitted events.

parentComponent.vue:

<script setup>
/**
 * Callback / listener function for the updateOrder emit event
 */
function updateOrderCallback (arg1, arg2) {
	console.log(arg1 + ' ' + arg2)
}
</script>
<template>
	<div>
		<Order @updateOrder="updateOrderCallback" />
	</div>
</template>

childComponent.vue:

<script setup>
// Declare the emit event 'updateOrder'
const emit = defineEmits(['updateOrder'])

function buttonClick () {
 // Trigger the emit event from Javascript.
 emit('updateOrder', arg1, arg2)
}
</script>
<template>
	<div>
 <!-- Two ways to trigger the emit event -->
		<button @click="$emit('updateOrder', arg1, arg2)">Click</button>
		<button @click="buttonClicked">Click to trigger the emit function in a function</button>
	</div>
</template>

This is the conceptual process how to build up the logic:

  1. Declare the const emit in your child component which call defineEmits() and pass your custom events as strings in an array. In my example I declared updateOrder.
  2. Add @updateOrder=updateOrderCallback as an inline arrow function where your child component is loaded in the parent component. @updateOrder refers to the custom declared emit event and updateOrderCallback is the callback method which is called when the emit event is triggered.

I hope this can help you out when you are trying to call a parent method from a child component in Vue 3!

More resources on the Vue $emit method

Vue.js
×

Success!

Help @sebastix spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Marika,
tipped: article
amount: 1000 SATS,

tipper: @hatem774,
tipped: article
amount: 1 SATS,

tipper: @nearjob,
tipped: article
amount: 1000 SATS,
)...