Vue3 Listen to event from dynamically created child component, $on replacement

Viewed 1050

I am creating a Vue component 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 component 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?

1 Answers

You 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 comp = h(Component, {
  onClick: e => console.log('click', e),
  onMyEvent: e => console.log('my-event', e),
})
createApp(comp, props).mount(div)

demo 1

If your project supports JSX, the equivalent is:

const comp = <Component onClick={e => console.log('click', e)}
                        onMyEvent={e => console.log('my-event', e)} />
createApp(comp, props).mount(div)

demo 2

Related