gpt4 book ai didi

Vue.js 自定义事件命名

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:05 25 4
gpt4 key购买 nike

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

当我从 child 触发事件时,我无法在 parent 那里收到它。

子组件

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

父组件

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

但是,当我在这两个地方将事件名称更改为 my-custom-event 时,它起作用了。

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

最佳答案

建议始终使用 kebab-case 来命名自定义事件。小写事件,全部拼在一起,正如@KoriJohnRoys 所推荐的那样也可以,但是更难阅读。事件命名不推荐使用camelCase

official documentation of Vue.JS在事件名称主题下声明以下内容:

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.

关于Vue.js 自定义事件命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42441952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com