Vue3中跨组件传值(Mitt)

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>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值