1.安装mitt
我使用的是yarn
yarn add mitt
2.在根目录下创建eventBus.js
// eventBus.js
import mitt from "mitt";
export const EventBus = mitt();
3.组件间进行传值与接收值
使用emit传值,使用on接收,最后不要忘记销毁,避免内存泄漏
<template>
<div class="parent">
<h3>A组件</h3>
<button @click="handleClick">传递Content值</button>
</div>
</template>
<script setup>
import { ref } from "vue";
import { EventBus } from "@/eventBus.js";
const content = ref("Hello Word");
const handleClick = () => {
EventBus.emit("change-content", content);
};
</script>
<style lang="scss" scoped>
.parent {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
<template>
<div class="nav">
<h2>B组件</h2>
<p>接受的数据:{{ contents }}</p>
</div>
</template>
<script setup>
import { EventBus } from "@/eventBus.js";
import { onMounted, onUnmounted, ref } from "vue";
const contents = ref("");
const handleMessage = (data) => {
console.log(data);
contents.value = data.value;
};
onMounted(() => {
EventBus.on("change-content", handleMessage);
});
onUnmounted(() => {
EventBus.off("change-content");
});
</script>
<style lang="scss" scoped>
.nav {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>