
全局事件总线的作用:
实现组件之间的通信,在A组件绑定事件(绑定的时候携带组件A的数据)在B组件调用。所以的事件都注册在EventBus中,供组件使用。
创建全局事件总线:
第一种写法,不推荐
const VC = Vue.extend();
const bus = new VC();
Vue.prototype.$bus = bus;
最终写法:
new Vue({
beforeCreate() {
Vue.prototype.$bus = this
}
}).$mount('#app')
注册事件
methods: {
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
},
使用事件
mounted() {
this.$bus.$on("hello", (data) => {
console.log("我是School组件,收到了数据", data);
});
},
// 如果不再使用这个组件,销毁之前解绑事件
beforeDestroy() {
this.$bus.$off("hello");
},
消息的订阅与发布
第三方库pubsub-js, 可以去GitHub找更好用的开源库。
使用步骤
npm i pubsub-js
使用
// 发布消息
sendStudentName() {
// this.$bus.$emit("hello", this.name);
pubsub.publish("hello", this.name);
},
// 订阅消息,第二个参数为真实数据,第一个参数为消息名
pubsub.subscribe("hello", function (a, b) {
console.log(b);
});
// 取消订阅
pubsub.unsubscrible(this.pubId)
需要注意的是:
subscribe这些方法里面的this并不会指向vc,可以使用箭头函数向外寻找this。也可以将回调函数定义在methods中传入。
pubsub.subscribe("hello", () => {});
methods : {
demo() {}
}
pubsub.subscribe("hello", this.demo(a, b));
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)