首先还是贴上代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vue demo</title> </head> <body> <script src="./vue.js"></script> <div id="app"> <receiver-comp></receiver-comp> <send-comp style="margin-top: 20px"></send-comp> </div> <script> const EventBus = new Vue(); let receiverComp = Vue.extend({ template: "<div>receive msg is: {{message}}</div>", data : function () { return { message: "default message" } }, created: function () { let self = this; EventBus.$on("updateMsg", function (msg) { self.message = msg; }) } }); Vue.component("receiver-comp", receiverComp); let sendComp = Vue.extend({ template: "<div><button @click='send'>send msg</button></div>", methods: { send: function () { EventBus.$emit("updateMsg", "hello vue by Event bus") } } }); Vue.component("send-comp", sendComp); let vue = new Vue({ el: "#app", data: { }, methods: { } }); </script> </body> </html>
EventBus
又称为事件总线。在Vue中可以使用 EventBus
来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件,但也就是太方便所以若使用不慎,就会造成难以维护的灾难,因此才需要更完善的Vuex作为状态管理中心,将通知的概念上升到共享状态层次
这个小例子是全局注册了两个组件,一个是发送消息组件,一个是接收消息组件。
猜测eventbus 中的$on $emit 方法是Vue 原型里面的方法。
所以我们new 一个Vue实例就可以使用了。