[VUE中的全局事件总线]

什么是全局事件总线

全局事件总线是一种组件间的通信方式,适用于任意组件间的通信

全局事件总线的作用

安装一个全局事件总线(GlobalEventBus)
new Vue({
    render:h => h(App),
    // 安装全局事件总线 GlobalEventBus
    beforeCreate(){
        // $bus 就是 当前应用的vm
        Vue.prototype.$bus = this
        console.log(this)
    }
}).$mount('#app')

应为全局事件总线用于任意组件间通信,所以在声明vue时就应当安装全局事件总线,this是声明Vue内的,所以该this指向的是vm本身而不是vc或者window

发送数据以及接受数据

我们有组件Student和组件School,两个组件是同等级别的,我们要做的是点击Student的按钮,把学生名给School组件,School组件收到数据并在控制台中输出姓名即可,因为是两个同等级组件的通信,使用全局事件总线是一个比较好的办法
组件Student:

<template>
    <div>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>
export default {
    name:'Student',
    data() {
        return {
            name:'张三',
            sex:'男'
        }
    },
    methods:{
        sendStudentName(){
            // 出发$bus全局总线名字叫hello的事件 并传参vc的name
            this.$bus.$emit('hello',this.name)
        }
    },
    mounted() {
        
    },
}

组件School:

<template>
    <div>
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>
export default {
    name:'School',
    data() {
        return {
            name:'南京大学',
            address:'南京'
        }
    },
    mounted() {
        // console.log('School',this) 
        // 向全局总线$bus绑定了一个单机事件($on)名字为hello,接受了一个数据data
        this.$bus.$on('hello',(data)=>{
            console.log('我是School组件,收到了数据',data)
        })
    },
    // 销毁之前
    beforeDestroy(){
        // 销毁之前销毁 hello事件
        this.$bus.$off('hello')
    }
}

从以上代码可以看出哪一个组件接受数据就在那一个组件绑定($on)自定义事件,事件回调在该组件自身
发送数据的组件触发事件($emit)

全局事件总线总结:

1.绑定自定义事件以及回调在接受数据的组件内完成,切记在生命周期销毁之前(beforeDestroy())要销毁相应的事件

mounted() {
		//向全局总线$bus绑定了一个单机事件($on)名字为hello,接受了一个数据data
        this.$bus.$on('hello',(data)=>{
            console.log('我是School组件,收到了数据',data)
        })
    },
    // 销毁之前
    beforeDestroy(){
        // 销毁之前销毁 hello事件
        this.$bus.$off('hello')
    }

2.在发送数据的组件内出发事件,并传入相应的参数,参数一为:出发的事件名,别的参数为:值

	methods:{
        sendStudentName(){
            // 出发$bus全局总线名字叫hello的事件 并传参vc的name
            this.$bus.$emit('hello',this.name)
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值