How to call a parent method from a child component in Vue 3 with <script setup>

dinsdag 1 augustus 2023 - 293 woorden, 2 min read

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

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!

Looking for the opposite? How to call a child method from a parent component.


Sebastian Hagens @Sebastix
I work as creative webdeveloper & tech consultant and care about digital freedoms. Follow me:
or visit my contact page