组件间的通信

兄弟组件之间如何通信

方法一、通过父组件通信

此方法需要保证兄弟组件 A、B 都在同一个父组件下;

父组件通过接受子组件A传递过来的事件消息,并调用子组件B

// 子组件 A
this.$emit('transmit', 'msg')
// 父组件
<ChildA @transmit="transmit"></ChildA>
<ChildB :msg="msg"></ChildB>

transmit (data) => {
    this.msg = data 
}
// 子组件 B、需要使用 watch 来监听父组件 props 穿过来的数据变化
watch (new, old) {
    数据操作... 
}

方法二、eventBus

通过创建Bus.js注册一个全局实例,通讯组件通过调用实例的方法达到通讯目的

创建 Bus.js

组件 A 导入 Bus.js 并 emit 消息

组件 B 导入 Bus.js 并在 mounted 中检测数据变化

Last updated

Was this helpful?