非父子组件间通讯

非父子组件之间的通讯,能够经过一个空的 Vue 实例做为中央事件总线(事件中心),用他来触发事件和监听事件。javascript

在这里,若是是工做中的新手看了官网的例子直接上手写,会有些发懵。这个做为事件总线空的 Vue 实例我该写哪里去?由于工做中咱们的组件都是互相独立的,不可能写一块儿的,做用域是不一样的,因此须要稍做调整html

1、在 main.js 中初始化根 Vue 以前,添加一个 data 对象,内写入一个名为 Event 的空 Vue 对象,也就是中央事件总线
new Vue({ el: '#app', data:{ Event: new Vue() }, render: h => h(App) }) 
2、在各组件中使用 Vue 的实例属性 $root 来访问咱们当前组件树的根 Vue 实例,这样就能够使用

vm.$root.Event 来访问咱们定义的事件发射器 Event
好比我在 Hello.vue 组件中想发送数据到 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 组件中进行接收java

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

这样就能够实现数据的通讯了api


 
非父子组件通讯
相关文章
相关标签/搜索