Vue.js $emit 和 $dispatch 有什么区别?
Vue.js what's the difference of $emit and $dispatch?
在 vue2.0 中,事件 $dispatch
和 $broadcast
已被弃用。
我发现 $dispatch
与 $emit
相似。
它们之间有什么区别?迁移的时候直接把$dispatch
替换成$emit
安全吗
不,您无法在所有地方用 $emit
替换 $disptach
。您可以替换它,无论您在哪里使用它进行从 child 到 parent 的通信,但对于其他情况,您可能必须采取其他方法。
来自documentation ( similar comments from Evan you in Upgrade Tips):
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
将通信传递给多层 parent 元素,你必须使用 $emit
以不同的方式处理该代码
在 vue2.0 中,事件 $dispatch
和 $broadcast
已被弃用。
我发现 $dispatch
与 $emit
相似。
它们之间有什么区别?迁移的时候直接把$dispatch
替换成$emit
安全吗
不,您无法在所有地方用 $emit
替换 $disptach
。您可以替换它,无论您在哪里使用它进行从 child 到 parent 的通信,但对于其他情况,您可能必须采取其他方法。
来自documentation ( similar comments from Evan you in Upgrade Tips):
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
将通信传递给多层 parent 元素,你必须使用 $emit
以不同的方式处理该代码