Vue.js $ emit和$ dispatch有什么区别? [英] Vue.js what's the difference of $emit and $dispatch?
问题描述
在vue2.0中,事件 $ dispatch
和 $ broadcast
已被弃用。
In vue2.0 the event $dispatch
and $broadcast
is deprecated.
我发现 $ dispatch
与 $ emit
相似。
他们之间有什么区别?迁移时,它可以直接将 $ dispatch
替换为 $ emit
。
What's the differences between them? Is it safe directly replacing $dispatch
into $emit
when migrating.
推荐答案
不,您将无法用 $ emit $替换
$ disptach
c $ c>无处不在您可以将其替换为从小孩到父母进行沟通的任何地方,但对于其他情况,您可能需要采取其他方法。
No, You will not be able to replace $disptach
with $emit
everywhere. You can replace it, wherever you are using it for communication from child to parent, but for other cases, you may have to take some other approach.
From the documentation ( similar comments from Evan you in Upgrade Tips):
这些方法最常见的用途之一是在父母与其直接孩子之间进行沟通。在这些情况下,您可以从v-on的小孩身上听到$ emit。这样可以让事件的便利性加上明确性。
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.
然而,当在遥远的后代/祖先之间进行通信时,$ emit不会帮助你。相反,最简单的升级就是使用集中的事件集线器。
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.
发送事件首先触发实例本身,然后沿着父链向上传播。当它触发父事件侦听器时,传播停止,除非该侦听器返回true。
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
So you can see, if you are passing communication to multiple layer of parent elements via $dispatch
, you have to handle that code differently with $emit
这篇关于Vue.js $ emit和$ dispatch有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!