全局事件总线

1、一种组件间通信方式,适用于任意组件间通信

2、安装全局事件总线:

$bus就是当前应用的vm

new Vue({

    ....
    beforeCreate() {
        Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    },
    ....
})

3、使用事件总线

1、接收数据:A组件想接受数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件本身

methods(){
    demo(data){.....}
}
......
mounted() {
    this.$bus.$on('xx',this.demo)
}

2、提供数据

this.$bus.$emit('xxxx',数据)

4、最好在beforeDestroy钩子中,用$off解绑当前组件所用到的事件

main.js

// 引入Vue
import Vue from 'vue'
// 引入App
import App from './App.vue'
// 关闭Vue生产提示
Vue.config.productionTip = false

/* const Demo = Vue.extend({})
const d = new Demo() */

// Vue.prototype.x = d

// 创建vm
new Vue({
    el:"#app",
    render: h => h(App),
    beforeCreate(){
        Vue.prototype.$bus = this //安装全局事件总线
    }
})

School组件



<template >
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>
    export default {
        name:'School',
        data(){
            return {
                name:'尚硅谷',
                address:'北京',
            }
        },
        mounted() {
            console.log('School',this)
            this.$bus.$on('hello',(data)=>{
                console.log('我是School组件,收到了数据',data);
            })
        },
        beforeDestroy() {
            this.$bus.$off('hello')
        },
    }
</script>

<style scoped>
    .school{
        background-color: skyblue;
        padding: 5px;
    }
</style>

Student组件



<template >
    <div class="school">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data(){
            return {
                name:'张三',
                sex:'男',
            }
        },
        mounted() {
            // console.log('Student',this.x)
        },
        methods:{
            sendStudentName(){
                this.$bus.$emit('hello',this.name)
            }
        }
    }
</script>

<style scoped>
    .school{
        background-color: orange;
        padding: 5px;
        margin-top: 30px;
    }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值