6

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!

3 Answers 3

8

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>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

How to pass and capture the data between emitter and listener? I am trying this.$emit('test', 'testdata').......onTest={(data) => {alert(data);}}.....but, it's not working.
4

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

1 Comment

Thank you for your answer! But I've already know it, my question is when I replace click to some non-native event, it will directly bind to DOM. What I want to achieve is like this.$on('custom-event', this.customEventHandler) will do.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.