对于父子(含跨级)传递数据的通信方式,Vue.js 并没有提供原生的 API 来支持,而是推荐使用大型数据状态管理工具 Vuex,但 Vuex 对于小型项目来说用起来真的很麻烦。并且在大型项目中如果仅仅只是极少的两个组件需要通行,用vuex也不友好
虽然vue2.0弃用了这两个方法,在很多基于 Vue 的 UI 框架中都有对其的封装,包括 element-ui、iview 。
那么 $dispatch 和 $broadcast 到底是怎么工作,其底层又是怎么实现的呢?接下来,我们就详细的说一说!
01 $dispatch 详解
为了追根溯源,我们还是先去 Vue 1.0 的文档你观摩一下其概念吧!
概念:
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. Any additional arguments will be passed into the listener’s
callback function.
上面的一段英文定义来自 Vue 1.0 官方文档,其大致的意思是说:dispatch 是一个事件,首先会在自己实例本身上触发,然后沿父链向上传播。当它触发父组件上的事件侦听器时传播即会停止,除非该侦听器返回 true。 任何其他