[聚合文章] 非父子组件间通信

JavaScript 1900-01-01 9 阅读

非父子组件之间的通信,可以通过一个空的 Vue 实例作为中央事件总线(事件中心),用他来触发事件和监听事件。

在这里,如果是工作中的新手看了官网的例子直接上手写,会有些发懵。这个作为事件总线空的 Vue 实例我该写哪里去?因为工作中我们的组件都是互相独立的,不可能写一起的,作用域是不同的,所以需要稍作调整

一、在 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>

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。