全局事件总线 —— 任意组件间通信
实现一个中介。
1.安装全局事件总线
new Vue({
el:'#app',
//将App组件放入容器中
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this //安装 $bus计算当前应用的vm
}
})
2.使用事件总线
①接收数据:A组件接收数据,则在A组件给$bus
绑定自定义事件,事件的回调留在A组件自身
methods(){
demo(data){}
},
mounted(){
this.$bus.$on('xxxx',this.demo)
}
或
mounted(){
this.$bus.$on('xxxx',(data)=>{
....
})
}
②提供数据
methods:{
ssss(){
this.$bus.$emit('xxxx',数据)
}
}