一、在 main.js 中初始化根 Vue 之前,添加一个 data 对象,内写入一个名为 Event 的空 Vue 对象,也就是中央事件总线

new Vue({
	el: '#app',
	data:{
		Event: new Vue()
	},
	render: h => h(App)
})

二、在各组件中使用 Vue 的实例属性 $root 来访问我们当前组件树的根 Vue 实例,这样就可以使用

vm.$root.Event 来访问我们定义的事件发射器 Event
比如我在 Hello.vue 组件中想发送数据到 Vue.vue 组件中

<template>
    <div class="hello">
        <h3>我是 {{name}} 组件</h3>
        <button @click="send">发送数据到Vue组件中</button>
    </div>
</template>

<script>
export default {
    data(){
        return {
            name: 'Hello'
        }
    },
    methods:{
        send(){
            // 触发组件 Hello 中的事件
                           // $emit(事件名,数据)
            this.$root.Event.$emit('hello',this.name)
        }
    }
}
</script>

在 Vue.vue 组件中进行接收

<template>
    <div class="Vue">
        <h3>我是 {{name}} 组件</h3>
    </div>
</template>

<script>
export default {
    data(){
        return {
            name: ''
        }
    },
    mounted(){
        // 在组件 Vue 创建的钩子中监听事件
                        // $on(事件名,数据)
        this.$root.Event.$on('hello',name => {
            this.name = name
        })
    }
}
</script>