Vue.js custom event naming

蹲街弑〆低调 提交于 2019-12-10 13:12:36

问题


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


回答1:


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.




回答2:


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

The docs for .sync recommend using the pattern update:my-prop-name




回答3:


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)




回答4:


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:



来源:https://stackoverflow.com/questions/42441952/vue-js-custom-event-naming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!