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,
vs <script setup>
).setup()
It took me more time than I wished, but this is my most simple code snippet with
and the Composition API style how to call a parent method from a child component with emitted events.<script setup>
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:
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
.@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!