xAoc
xAoc

Reputation: 3588

Vue.js custom event naming

I have two components, one contains another.

And when I trigger event from child I can't receive it in parent.

Child component

this.$emit('myCustomEvent', this.data);

Parent component

<parent-component v-on:myCustomEvent="doSomething"></parent-component>

But, when I changed event name to my-custom-event in both places it works.

Vue somehow transform event names? Or what can be a problem? I read docs about component naming convention but there nothing related to event naming

Upvotes: 22

Views: 24937

Answers (4)

Nicholas Albion
Nicholas Albion

Reputation: 3284

In addition to @ssc-hrep3's point on kebab-case

The docs for .sync recommend using the pattern update:myPropName

Upvotes: 7

ssc-hrep3
ssc-hrep3

Reputation: 16069

It is recommended to always use kebab-case for the naming of custom events. Lower case events, all smashed together, as recommended by @KoriJohnRoys would also work but are harder to read. It is not recommended to use camelCase for event naming.

The official documentation of Vue.JS states the following under the topic of Event Names:

Event Names

Unlike components and props, event names don’t provide any automatic case transformation. Instead, the name of an emitted event must exactly match the name used to listen to that event. For example, if emitting a camelCased event name:

this.$emit('myEvent')

Listening to the kebab-cased version will have no effect:

<my-component v-on:my-event="doSomething"></my-component>

Unlike components and props, event names will never be used as variable or property names in JavaScript, so there’s no reason to use camelCase or PascalCase. Additionally, v-on event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to.

For these reasons, we recommend you always use kebab-case for event names.

Upvotes: 46

euvl
euvl

Reputation: 4786

Vue.js transforms not only xml tags (component names) but attributes as well, so when you are generating event

$emit('iLikeThis')

you must handle it as:

v-on:i-like-this="doSomething"

From docs:

When registering components (or props), you can use kebab-case, camelCase, or TitleCase. ...

Within HTML templates though, you have to use the kebab-case equivalents:

Upvotes: -6

Kori John Roys
Kori John Roys

Reputation: 2661

For custom events, the safest option is to just use a lower-cased event name all smashed together. Currently even kebab-case can have issues.

this.$emit('mycustomevent', this.data);

then, in the parent component, feel free to bind to a camel-cased function

<parent-component v-on:mycustomevent="doSomething"></parent-component>

it's a bit janky, but it works.

Source (states that kebab-case doesn't work either)

Upvotes: 1

Related Questions