一般如果父子组件的情况,我们会使用$emit与@on来进行传值,但是如果组件的层级比较多,有了孙级组件甚至更深。
那我们向上一层层的传递是不是很麻烦,这个时候我们就可以使用eventBus来做!
1.在顶层组件中引入vue 然后new一个vue实例
import Vue from 'vue' data:()=>({ eventBus: new Vue() }),
2.使用依赖注入
//顶层组件 provide:function(){ //依赖注入 return { eventBus:this.eventBus } }, //子孙组件 inject:['eventBus'],
在你的任何子孙组件中使用inject 就可以拿到eventBus
3.利用eventBus向上传值
this.eventBus.$emit('update:selected',参数1,参数2)
4.上层组件接收传值
this.eventBus.$on('update:selected',(a,b)=>{ console.log(a,b) })
eventBus就是利用Vue实例做了一个事件中心,只要组件里面inject了,就可以利用this.eventBus实现跨组件层级的传值,再也不需要一层层的传递了。