关于javascript:Vue.js $ emit和$ dispatch有什么区别?

Vue.js what's the difference of $emit and $dispatch?

在vue2.0中,不赞成使用事件$dispatch$broadcast

而且我发现$dispatch$emit类似。

它们之间有什么区别? 迁移时将$dispatch直接替换为$emit是否安全?


不,您将无法在任何地方用$emit替换$disptach。 您可以在任何地方使用它进行替换,以便在孩子与父母之间进行通信,但是对于其他情况,则可能必须采取其他方法。

从文档中(升级提示中Evan的类似评论):

One of the most common uses for these methods is to communicate between a parent and its direct children. In these cases, you can actually listen to an $emit from a child with v-on. This allows you to keep the convenience of events with added explicitness.

However, when communicating between distant descendants/ancestors, $emit won’t help you. Instead, the simplest possible upgrade would be to use a centralized event hub.

从$ dispatch的文档中

Dispatch an event, first triggering it on the instance itself, and then propagates upward along the parent chain. The propagation stops when it triggers a parent event listener, unless that listener returns true.

另一方面$ emit:

Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.

因此,您可以看到,如果要通过$dispatch将通信传递给多层父元素,则必须使用$emit来不同地处理该代码。