'EventTester.vue' child component:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<template> <a href="#" @click.prevent="callOnTesting">Click me</a> <div>Hello from EventTester</div> </template> <script setup> const emit = defineEmits(['onTesting']) const callOnTesting = () => { const obj = {color: 'blue', length: '77 feet'} emit('onTesting', obj) } </script> |
The child component publishes an event handler with the defineEmits
macro. The defineEmits
argument is an array of handler to publish.The defineEmits() macro cannot be used inside a function, it must be placed directly within <script setup>
, as show here.
Read more about Vue.js 3 component events here.
To call the onTesting
method passed in from the parent:
1 |
emit('onTesting', [optional arguments]) |
'App.vue' parent component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<template> <div> <EventTester @onTesting="testing" /> </div> </template> <script setup> import EventTester from './components/EventTester.vue' const testing = (obj) => { console.log(`Received object from child:`) console.log(obj) } </script> |
The parent component passing a method with the @onTesting
handler. The method passed will be called from the child with the emit
call.