全局事件总线

全局事件总线可以实现任意组件间的通信

Vue 原型对象上包含事件处理的方法
1) $on(eventName, listener): 绑定自定义事件监听
2) $emit(eventName, data): 分发自定义事件
3) $off(eventName): 解绑自定义事件监听
4) $once(eventName, listener): 绑定事件监听, 但只能处理一次
所有组件实例对象的原型对象的原型对象就是 Vue 的原型对象
1) 所有组件对象都能看到 Vue 原型对象上的属性和方法
2) Vue.prototype.$bus = new Vue(), 所有的组件对象都能看到$bus 这个属性对象

指定事件总线对象

在mian.js文件中设置事件总线

new Vue({
  beforeCreate () { // 尽量早的执行挂载全局事件总线对象的操作 
    Vue.prototype.$bus = this 
  },
  router,
  store,
  render: h => h(App)
}).$mount('#app')

student.vue

<template>
    <div class="student">
        <h2>姓名:{{name}}</h2>
        <h2>性别:{{sex}}</h2>
        <button @click="sendStudentName">把姓名给班级组件</button>
    </div>
</template>

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

school.vue组件

<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>

 

posted @ 2022-03-07 23:48  keyeking  阅读(245)  评论(0编辑  收藏  举报