Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 408
zl2003cn Avatar asked May 01 '17 13:05

zl2003cn


People also ask

Can you use JSX with Vue?

js. Love it or hate it, JSX is a popular extension to JavaScript that allows XML tokens in your scripts. If you want to create templates in your script files and you find Vue's render() function to be difficult to work with, JSX may be just what you need.

What does $emit do in Vue?

$emit to emit a custom event. Let's take a look at an example where we have MyTextInput. vue that contains a label and a text input. Whenever the text changes, we want to emit an event with the uppercased value of our input. Instead of calling $emit from our template, we can call a component method instead.

How do you emit an event to a child component Vue?

We can emit an event from the parent component to the child with the $emit method. However, there's no obvious way to emit an event from parent to child. However, we can still do this. We can create a new Vue instance create an event bus and then pass the Vue instance to the child to listen to it.

What is $listeners Vue?

Using the $listeners property, you can forward all event listeners on the component to a specific child element with v-on="$listeners" . For elements like <input> , that you also want to work with v-model , it's often useful to create a new computed property for listeners, like inputListeners below: Vue.


3 Answers

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>
    );
}
like image 110
L. Albano Avatar answered Nov 10 '22 10:11

L. Albano


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>,
  )
}
like image 36
Roy J Avatar answered Nov 10 '22 09:11

Roy J


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

like image 28
Liang Zhou Avatar answered Nov 10 '22 11:11

Liang Zhou