javascript - Vue.js $emit 和 $dispatch 有什么区别?

标签 javascript events mvvm vue.js vuejs2

在 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/

相关文章:

javascript - 可排序的 li 和自动排序的 div jquery

wpf - 在数据绑定(bind)流文档中插入分隔符(空行)

c# - 使用事件来集中信息

jQuery 在绑定(bind) .load() 事件之前检查图像是否已加载

java - 我可以并且应该在 GWT 中测试 fireEvent 和 Handlers 方法吗?

android - 如何在Android上的RxJava中通过平面图向下发送自定义可弃项?

c# - 为透明的点击覆盖寻找一个好的 WPF 解决方案

javascript - 将 js 变量值添加到输入字段

javascript - 无法从 $.ajax 迭代 json 数组

javascript - 在 Canvas 中翻转 Sprite