在 vue2.0 中,事件 $dispatch
和 $broadcast
被弃用。
而且我发现 $dispatch
和 $emit
很相似。
它们之间有什么区别?迁移时直接将 $dispatch
替换为 $emit
是否安全。
最佳答案
不,您不能在任何地方用$emit
替换$disptach
。您可以替换它,无论您将它用于从 child 到 parent 的通信,但对于其他情况,您可能必须采用其他方法。
来自documentation (来自 Evan you 在 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
将通信传递给多层父元素,则必须使用 $emit
以不同方式处理该代码
关于javascript - Vue.js $emit 和 $dispatch 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923555/