Vue中子组件之间的通信
最近使用vue,学习了父组件向子组件以及子组件向父组件通信的内容,但是在实际的应用中遇到了问题,如何进行同级组件之间的通信呢,后来在网上找了相关资料,一般推荐用vuex和bus事件两种方式,我选了bus总线,即中央事件总线。
- 创建bus总线
新建一个bus.js文件(其实就是建立一个公共的js文件,专门用来传递消息),文件位置根据需要自定义,本文将该js文件放置到src/components/common目录下,具体内容为:
import Vue from 'vue';
// 使用 Event Bus
const bus = new Vue();
export default bus;
- 组件1引用bus总线 (发送消息)
//component1.vue
<template>
<div>
<button @click="bus">按钮</button>
</div>
</template>
import bus from './bus.js'
export default {
data() {
return {
message: ''"
}
},
methods: {
bus () {
bus.$emit('msg', '接收消息了,大哥!!!')
}
}
}
这里的bus.$emit(‘msg’, ‘接收消息了,大哥!!!’)代码部分为发送消息,即向公共组件bus中发布一个名称为:msg,参数为“接收消息了,大哥!!!”的事件。
3.组件2引用bus组件(接收消息)
//component2.vue
<template>
<div id="mess">
<p>兄弟我接收的消息是:{{messages}}</p>
</div>
</template>
import bus from './bus.js'
export default {
data() {
return {
message: ''
}
},
mounted() {
bus.$on('msg', (e) => {
this.message = e
})
}
}
这里的 bus.$on(‘msg’, (e) => })为接收bus总线中的msg事件,其中参数为e为传过来的参数,即“接收消息了,大哥!!!”。最后在组件component2中显示的内容为:
兄弟我接收的消息是:接收消息了,大哥!!!
还请各位多多指教,交流