最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue3 Listen to event from dynamically created child component, $on replacement - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

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 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')
  }
})

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论