vue3非直接组件之间的通信(eventBus)

1. 使用 EventBus

// eventBus.ts
import { reactive } from 'vue'

const EventBus = reactive({
  events: {} as any,
  emit (event:any, data:any) {
    this.events[event] &&
      this.events[event].forEach((callback:any) => callback(data))
  },
  on (event:any, callback:any) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
  }
})

export default EventBus

2 EventBus实现组件通信

在需要的组件中使用:

<!-- ComponentA.vue -->
<template>
  <button @click="sendEvent">发送事件</button>
</template>

<script setup>
import EventBus from './eventBus';

function sendEvent() {
  EventBus.emit('event-from-a', 'Hello from Component A!');
}
</script>

<!-- ComponentB.vue -->
<template>
  <div>{{ receivedData }}</div>
</template>

<script setup>
import EventBus from './eventBus';
import { ref, onMounted } from 'vue';

const receivedData = ref('');

onMounted(() => {
  EventBus.on('event-from-a', (data) => {
    receivedData.value = data;
  });
});
</script>

这个方法使用了简单的 EventBus 机制,使 ComponentA.vue 组件可以通过 emit 事件发送消息,而 ComponentB.vue 组件可以通过 on 监听相应的事件。

3、 其他方法

可以借助父组件或者更现代的状态管理工具。在父组件中定义一个共享的状态,然后通过 props 将状态传递给两个兄弟组件:

<!-- Parent.vue -->
<template>
  <div>
    <BrotherA @updateSiblingData="updateData" />
    <BrotherB :siblingData="siblingData" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import BrotherA from './BrotherA.vue';
import BrotherB from './BrotherB.vue';

const siblingData = ref('');

function updateData(newData) {
  siblingData.value = newData;
}
</script>
<!-- BrotherA.vue -->
<template>
  <div>
    <h2>兄弟组件 A</h2>
    <button @click="sendData">发送数据到兄弟 B</button>
  </div>
</template>

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits();

function sendData() {
  emit('updateSiblingData', 'Data from Brother A');
}
</script>
<!-- BrotherB.vue -->
<template>
  <div>
    <h2>兄弟组件 B</h2>
    <p>来自兄弟 A 的数据: {{ siblingData }}</p>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  siblingData: String
});
</script>

在此示例中,BrotherA.vue 组件通过事件更新父组件中的 siblingData,而 BrotherB.vue 则通过 props 接收这个数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值