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!
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.
$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.
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.
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.
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>
);
}
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>,
)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With