vue + ts 实现组件间通信

37 阅读1分钟

vue + ts 实现组件间通信

我们知道,在vue中, 父子组件的通信可以通过props与emit搞定, 那么组件之间的通信又可以如何解决呢
首先npm install mitt安装 mitt 用于构建事件总线
然后创建EventBus.ts, 在该文件中构造事件总线实例

import mitt from 'mitt';

type Events = {
  customEvent: string; // 可以扩展更多事件
};
const bus = mitt<Events>();
export default bus;

接下来就只需要在需要通信的组件间使用即可, 下面准备了两个同级组件

// src/components/Child1.vue

<template>
  <div @click="emitEvent">点我发送事件</div>
</template>

<script setup lang="ts">
import bus from "../utils/EventBus";

function emitEvent() {
  bus.emit("customEvent", "我是从 Child1 发的消息");
}
</script>

<style scoped>
div {
  width: 100px;
  height: 100px;
  margin: 20px;
  border: 1px solid #000;
}
</style>

// src/components/Child2.vue
<template>
  <div>
    <h3>来自Child1的消息</h3>
    {{ customEvent }}
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
import bus from "../utils/EventBus";

let customEvent = ref("");

function handleEvent(msg: string) {
  customEvent.value = msg;
  console.log("Child2 收到消息:", msg);
}

onMounted(() => {
  bus.on("customEvent", handleEvent);
});

onUnmounted(() => {
  bus.off("customEvent", handleEvent);
});
</script>

<style scoped>
div {
  width: 100px;
  height: 100px;
  margin: 20px;
  border: 1px solid #000;
}

h3 {
  font-size: 13px;
  color: blue;
}
</style>

如此, 我们通过bus.emit()来发送消息, 通过bus.on()bus.off()接收处理与关闭消息即可