兄弟没有共同的父级
创建空的Vue实例对象
// main.js
// 创建空的Vue实例
var eventBus = new Vue()
// 把Vue空实例挂载到Vue的原型上面
Vue.prototype.eventBus = eventBus
创建a组件
<template>
<div>
我是child - a组件
<button>传递数给b组件</button>
</div>
</template>
创建b组件
<template>
<div>
我是child - b组件
</div>
</template>
在a组件中通过this.eventBus.$emit进行数据的传递
this.eventBus.$emit('sendData', this.dataA)
在b组件中通过this.eventBus.$on进行数据的监听接收
this.eventBus.$on('sendData', val => {
this.receiveData = val
})
完整代码
// main.js
// 创建空的Vue实例
var eventBus = new Vue()
// 把Vue空实例挂载到Vue的原型上面
Vue.prototype.eventBus = eventBus
<!-- a.vue -->
<template>
<div>
我是child - a组件
<button @click="send">传递数给b组件</button>
</div>
</template>
<script>
export default {
data() {
return {
dataA: '我是a组件中的数据'
}
},
methods: {
send() {
this.eventBus.$emit('sendData', this.dataA)
}
}
}
</script>
<!-- b.vue -->
<template>
<div>
我是child - b组件:{{ receiveData }}
</div>
</template>
<script>
export default {
data() {
return {
receiveData: ''
}
},
// 声明周期:当组件加载完毕就执行,但是此时DOM节点还是虚拟的
created() {
// sendData:在a组件自定义事件名
// function中的val就是形参,代表的就是a组件中传递过来的实参// 这里的this指向的是Vue实例
this.eventBus.$on('sendData', val => {
this.receiveData = val
})
}
}
</script>
总结
空实例方法比较简介,它有一个最大的特点就是不用分析组件的结构嵌套关系。你无需关注是否有共同的父级,因为这种通信方式是只要知道哪两个组件需要通信就可以了,一个组件设置$emit,另一个组件$on监听即可。如果项目大了用的多了容易乱套。这个问题需要Vuex(终极解决方案)来解决