VUE 学习之Event Bus

首先还是贴上代码:

<!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实例就可以使用了。 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值