Vue学习:Vue中的全局事件总线和消息的订阅与发布

Vue中的全局事件总线和消息的订阅与发布都是可以实现组件间的相互通信。

一、全局事件总线

Vue中的全局事件总线可以任意组件间的相互通信,其原理就是创建一个东西能够让所有的组件和vm都能识别到,这个东西就可以叫做全局事件总线。

首先需要安装全局事件总线,也就是在main.js中添加beforeCreated生命周期钩子,因为此时模板还未解析,所以选择这个时候安装总线,具体代码是:

new Vue({

el:'#app',

render: h => h(App),

beforeCreate() {

Vue.prototype.$bus=this

},

}).$mount('#app')

发送方发送数据:

通过在methods中编写一个方法,然后通过:this.$bus.$emit传递数据;

接收方接收数据:

在mounted中通过:this.$bus.$on接收数据。

例子:

发送方Student组件:

<template>

<!-- 组件的结构 -->

<div class="student">

    <h2>{{name}}</h2>

    <h2>{{age}}</h2>

    <button @click="sendStudentName">把学生名给school</button>

</div>

</template>

<script>

export default{

    name:'StudentName',

     data(){//data一定要写成函数的形式

                return {

                    name:'tom',

                    age:18,

                }

            },

    methods:{

        sendStudentName(){

            this.$bus.$emit('hello',this.name)

        }

    }

}

</script>

<style>

.student{

    background-color: greenyellow;

}

</style>

接收方School组件:

<template>
<!-- 组件的结构 -->
<div class="demo">
    <h2>{{schoolName}}</h2>
    <h2>{{address}}</h2>
</div>
</template>
<script>
        export default {
            name:'SchoolName',
            data(){//data一定要写成函数的形式
                return {
                    schoolName:'河南',
                    address:'洛阳',
                }

            },
            mounted(){
                console.log('school',this);
                this.$bus.$on('hello',(data)=>{
                    console.log('school组件,收到了数据',data);
                })
            },
            beforeDestroy(){
                this.$bus.$off('hello')
            }

        }
</script>

二、消息的订阅与发布

实现消息的订阅与发布,首先需要安装一个库,可以选择安装pubsub-js库;

第一步:引入pubsub-js库:import pubsub from 'pubsub-js'

第二步:订阅方订阅消息:

mounted(){

                this.pubId=pubsub.subscribe('hello',function(msgName,data){

                    console.log('发布了hello消息',msgName,data);

                })

            },

第三步:发布方发布消息:

 methods:{

        sendStudentName(){

            pubsub.publish('hello',this.name)

        }

    }

如果需要取消订阅:

beforeDestroy(){

                // this.$bus.$off('hello')

                pubsub.unsubscribe(this.pubId)

            }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值