全局事件总线

vue2中的一种组件通信方式,适用于任意组件间,如子孙、兄弟、父子等不同关系的组件间的通信 。

1、全局事件总线的条件

  • 所有组件都能看到这个总线对象
  • 这个对象能访问$emit、$on方法

因此,通常用vm对象作为全局事件总线来使用。

2、安装全局事件总线,入口文件为main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  // 安装全局事件总线
  //$bus指向vm
  beforeCreate(){
    Vue.prototype.$bus = this
  },
}).$mount('#app')

3、使用全局事件总线

关键:确定好接收数据的一方和提供数据的一方。

①接收数据:组件想接收数据,则在组件中给$bus绑定自定义事件,事件的回调留在组件自身。

<template>
    <div class="demo">
        <h2>我是Demo组件:{{sth}}</h2>
        <h3>收到的数据:{{data}}</h3>
    </div>
</template>
<<script>
    export default {
        name:'Demo',
        data() {
            return {
                sth:'Demo的sth',
                data:''
            }
        },
        methods: {
            receiveMsg(data1){
                console.log('Demo组件收到数据了',data1)
                this.data = data1
            }
        },
        // 利用mounted钩子,绑定自定义事件,接收数据,收到Exam组件的数据
        mounted() {
            this.$bus.$on('demo',this.receiveMsg)
        },
    }
</script>
<style>
    .demo{
        color: pink;
    }
</style>

②提供数据

<template>
    <div class="exam">
        <h2>我是Exam组件:{{msg}}</h2>
        <button @click="sendMsg">点击发送数据给Demo组件</button>
    </div>
</template>
<<script>
    export default {
        name:'Exam',
        data() {
            return {
                msg:"Exam的msg"
            }
        },
        methods: {
            sendMsg(){
                // 发送数据,触发自定义事件,将msg的内容发送给Demo组件
                this.$bus.$emit('demo',this.msg)
            }
        },
    }
</script>
<style>
    .exam{
        color: skyblue;
    }
</style>

注:这里举的例子是兄弟关系的组件。

4、解绑事件

beforeDestroy() {
    //不传参时则解绑所有自定义事件
    this.$bus.$off('demo')
},

5、Vue与VueComponent的关系

VueComponent.prototype.__proto__ === Vue.prototype
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值