bakis
bakis

Reputation: 675

How to pass event listener to the root component?

I am using vue3 and I know that when working with components you can pass listener callbacks using v-on directive or use its shorthand @ (like in the example below).

<my component @click="myCallback"/>

But is there a way to pass them to the app (root component)?

import { createApp } from 'vue'
// import the root component App from a single-file component.
import MyComponent from './MyComponent.vue'

const app = createApp(MyComponent, {props})

Upvotes: 4

Views: 1525

Answers (2)

Tolbxela
Tolbxela

Reputation: 5181

You are not passing callbacks to the components, but reacting to events from them. If you want to react on some event in the Vue root app, then just define v-ons in the root template.

So, for your example:

If you put your component into the app template and define the callback as app method, then your method will be called when the event occurs.

App

<template>
    <my component @click="myCallback"/>
</template>

and

methods: {
    myCallback(event) {
    ....
    }
}

Example

const MyComp = {
  emits: ['click'],
  template: `<button id="my-button" @click="$emit('click', $event)">Click me!</button>`
}

const App = {
 components: { MyComp },
 methods: {
    myCallback(event){
        alert('Clicked button: ' + event.target.id)
    }
  }
}

Vue.createApp(App).mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  <my-comp @click="myCallback"></my-comp> 
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222910

v-on-* template syntax is translated to on* props in h function, which is used to create vnodes. Considering that MyComponent emits foo event, it's:

const app = createApp(MyComponent, { onFoo() {...} })

Upvotes: 6

Related Questions