原理
它的原理是给 Vue 的原型对象上面添加一个属性。这样的话我所有组件的都可以访问到这个属性,然后可以通过这个属性来访问其他组件给这个属性上面绑定的一些方法,从而去传递数据。而且这个属性还可以去访问 Vue 实例对象上的方法。因为 Vue 组件构造函数的原型对象的原型对象是指向 Vue 的原型对象的
全局事件总线(GlobalEventBus)
一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件
- 所有的组件对象都必须能看见他
- 这个对象必须能够使用 $on $emit $off 方法去绑定、触发和解绑事件
3.使用事件总线:
①.接收数据:A组件想接收数据,则在A组件中给 $bus 绑定自定义事件,事件的回调留在A组件自身
methods(){
demo(data){......}
}
......
mounted() {
//给$bus绑定hello事件
this.$bus.$on("xxx",this.demo)
//或者
//this.$bus.$on("xxx",(data)=>{
console.log("执行事件")
})
}
或者不写上边的 method,直接写成一个箭头函数
②.B组件 提供数据:this. b u s . bus. bus.emit( " xxx",数据)
4.最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
使用
1,定义全局事件总线
在main.js中定义
new Vue({
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this//安装全局事件总线,$bus就相当于当前vm
}
}).$mount('#app')
2,使用事件总线
School.vue 中给 $bus 绑定 demo事件
<template>
<!--组件的结构-->
<div class="school">
<h2>学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
<span>传过来的消息:{{ msg }}</span>
</div>
</template>
<script>
import pubsub from "pubsub-js";
//组件交互相关的代码(数据、方法等)
export default {
name: "SchoolD",
data() {
return {
name: "北京大学",
address: "北京",
msg: "",
};
},
mounted() {
this.$bus.$on("demo", (data) => {
console.log("我是school组件,到了数据:" + data);
});
this.pubid = pubsub.subscribe("hello", (msgName, data) => {
this.msg = data;
console.log(
"有人发布了hello消息," + msgName + "回调执行了,收到数据:" + data
);
});
},
beforeDestroy() {
pubsub.unsubscribe(this.pubid);
this.$bus.$off("demo");//最好在销毁前 解绑事件
},
methods: {
// hello(msgName, data) {
// //两个参数 第一个是方法名 第二个是传过来的数据
// this.msg = data;
// console.log(
// "有人发布了hello消息," + msgName + "回调执行了,收到数据:" + data
// );
// },
},
};
</script>
3,在student 组件中触发事件
<template>
<!--组件的结构-->
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生年龄:{{ age }}</h2>
<button ="send">向School组件发送学生姓名</button>
</div>
</template>
<script>
// import pubsub from "pubsub-js";
//组件交互相关的代码(数据、方法等)
export default {
name: "StudentD",
data() {
return {
name: "张三",
age: 18,
};
},
methods: {
// sendStudentName() {
// pubsub.publish("demo", 666);
// },
send() {
this.$bus.$emit("demo", "张三");
},
},
};
</script>
4,结果