I am creating a Vue ponent dynamically and I want to listen to an event that it emits. I know you can use the @eventName
in the markup but I am creating the ponent using createApp
.
const div = document.createElement('div');
this.$refs.login.appendChild(div);
let props = {
/** some props **/
};
createApp(Component, props,).mount(div);
This is how I create the Component
. This answer here works for my problem but it for Vue2 and the $on
has been removed in Vue3.
How can I achieve this using Vue3?
I am creating a Vue ponent dynamically and I want to listen to an event that it emits. I know you can use the @eventName
in the markup but I am creating the ponent using createApp
.
const div = document.createElement('div');
this.$refs.login.appendChild(div);
let props = {
/** some props **/
};
createApp(Component, props,).mount(div);
This is how I create the Component
. This answer here works for my problem but it for Vue2 and the $on
has been removed in Vue3.
How can I achieve this using Vue3?
Share Improve this question edited May 13, 2021 at 11:39 kks21199 asked May 13, 2021 at 9:34 kks21199kks21199 1,1462 gold badges11 silver badges31 bronze badges 1- One thing I can think of is to pass a callback as a prop and then execute that in the child ponent, but that seems a bit messy. – kks21199 Commented May 13, 2021 at 9:34
2 Answers
Reset to default 4You could use a render function (h
) to add the event handler. The second argument to h
is an object whose keys beginning with "on"
are treated as event handlers. For example, to add handlers for the click
event and for an event named my-event
:
import { h } from 'vue'
const p = h(Component, {
onClick: e => console.log('click', e),
onMyEvent: e => console.log('my-event', e),
})
createApp(p, props).mount(div)
demo 1
If your project supports JSX, the equivalent is:
const p = <Component onClick={e => console.log('click', e)}
onMyEvent={e => console.log('my-event', e)} />
createApp(p, props).mount(div)
demo 2
If your emitting from the child you can use this.
Root Component Events# Static event listeners can be added to the root ponent by passing them as props to createApp:
createApp(App, {
// Listen for the 'expand' event
onExpand() {
console.log('expand')
}
})