zl2003cn
zl2003cn

Reputation: 485

Binding custom event with Vue 2 and JSX

I want to bind custom event on root tag instead of binding it in mounted(). So I try the following code:

render (h) {
  return (
    <div on-custom-event={this.handleCustomEvent}></div>
  )
}

But when I run it with Chrome, I found that custom-event was bound to DOM which cannot be fired using $emit, but with VueJS 2's template syntax it is easy to do:

<template>
   <div @custom-event="handleCustomEvent"></div>
</template>

Please help me on this problem, thanks!

Upvotes: 6

Views: 6010

Answers (3)

Liang Zhou
Liang Zhou

Reputation: 2165

Suppose your custom event is custom-event. Try either one of the following:

  • onCustom-event
  • on-custom-event

I found them here: https://github.com/vuejs/babel-plugin-transform-vue-jsx/issues/164

Upvotes: 1

L. Albano
L. Albano

Reputation: 181

A little bit late for the party but...

To trigger the event you need to something like:

protected render(h: any) {
    return (
        <a onClick={(e: any) => this.$emit('test')}>
            {this.$slots.default}
        </a>
    );
}

To listen to the event:

protected render(h: any) {
    return (
        <NavLink onTest={() => alert('clicked')}>
            <i class='fa fa-bars'></i>
        </NavLink>
    );
}

Upvotes: 8

Roy J
Roy J

Reputation: 43899

According to example in the docs, the JSX event handler should be camel-case, not kebab-case, so try something like:

render (h) {
  return (
    <div onCustomEvent={this.handleCustomEvent}></div>,
  )
}

Upvotes: 4

Related Questions