Vue.js 自定义事件命名 [英] Vue.js custom event naming

查看:73
本文介绍了Vue.js 自定义事件命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件,一个包含另一个.

I have two components, one contains another.

当我从孩子触发事件时,我无法在父母中收到它.

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

子组件

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

父组件

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

但是,当我在两个地方将事件名称更改为 my-custom-event 时,它都可以工作.

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

Vue 以某种方式转换事件名称?或者有什么问题?我阅读了 docs 关于组件命名约定,但没有与事件相关的内容命名

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

推荐答案

建议始终使用 kebab-case 为自定义事件命名. 小写事件,按照@KoriJohnRoys 的建议,全部粉碎在一起也可以使用,但更难阅读.不建议使用 camelCase 进行事件命名.

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.

Vue.JS 的官方文档 指出事件名称主题下的以下内容:

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')

听 kebab-cased 版本没有效果:

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

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

与组件和道具不同,事件名称永远不会在 JavaScript 中用作变量或属性名称,因此没有理由使用驼峰式大小写或 PascalCase.此外,DOM 模板中的 v-on 事件侦听器将自动转换为小写(由于 HTML 不区分大小写),因此 v-on:myEvent 将变为 v-on:myevent – 使 myEvent 无法侦听.

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.

出于这些原因,我们建议您始终使用 kebab-case 作为事件名称.

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

这篇关于Vue.js 自定义事件命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆