Vue3 组件间通信- mitt实现任意组件间通信

pnpm install mitt

mitt 主要有4个API:emit(触发某个事件)、on(绑定事件)、off(解绑某个事件)、all(获取所有绑定的事件)

使用步骤:

(1)main.js中将mitt全局注册

(2)在A组件中emit 发射事件(发射信号) 

(3)在B组件中监听事件

(4)移除监听

main.js 中通过 app.config.globalProperties 将 mitt 实例注册为全局属性。整个应用中的任何组件都可以方便地访问和使用事件总线,无需单独引入。

//main.js

import { createApp } from 'vue';
import App from './App.vue';
import mitt from 'mitt';

const app = createApp(App);

// 将 mitt 实例挂载到全局属性
app.config.globalProperties.$bus = mitt();

app.mount('#app');

App.vue 简版写法

<template>
  <div>
    <div v-if="showTaskLog">Task Log is shown</div>
    <ChildComponent />
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';

const showTaskLog = ref(false);            //显示/隐藏日志
const { proxy } = getCurrentInstance();    //setup 中可以通过 proxy 获取全局属性

proxy.$bus.on('show-task-log', data => { showTaskLog.value = true;});    //监听'show-task-log' 事件, 发生show-task-log事件就执行()=>{ showTaskLog.value = true;}
</script>


<!--

此方案没有使用 onUnmounted 来管理事件监听器的生命周期,潜在的内存泄漏问题。注册到全局变量,不会因为组件销毁而销毁,内存没有得到释放。

如果在组件卸载时你不需要移除事件监听器,或者你确定事件监听器的生命周期与组件的生命周期一致,这种简化方式是可以的。

-->

 推荐使用 onMountedonUnmounted ,这样可以确保组件卸载时不会出现内存泄漏。

App.vue 推荐写法

<!--App.vue-->

<template>
  <div>
    <div v-if="showTaskLog">Task Log is shown</div>
    <ChildComponent />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue';

const showTaskLog = ref(false);
const { proxy } = getCurrentInstance();

onMounted(() => { proxy.$bus.on('show-task-log', ()=> {showTaskLog.value = true;});});

onUnmounted(() => { proxy.$bus.off('show-task-log');}); // 不指定移除哪个回调函数,就移除监听show-task-log的绑定的所有回调函数。
</script>

如果多个回调函数监听同一个事件,而onUmounted时只想移除特定的回调函数则需要这样写:

const handleShowTaskLog = () => {
  console.log('handleShowTaskLog called');
};

const anotherHandler = () => {
  console.log('anotherHandler called');
};

onMounted(() => {
  proxy.$bus.on('show-task-log', handleShowTaskLog);
  proxy.$bus.on('show-task-log', anotherHandler);
});

onUnmounted(() => {
  proxy.$bus.off('show-task-log', handleShowTaskLog);
  // 这样可以确保 only handleShowTaskLog 被移除,而 anotherHandler 仍然会被触发
});

发射

<template>
  <button @click="triggerAsyncFunction">Show Task Log</button>
</template>

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

const { proxy } = getCurrentInstance();

const triggerAsyncFunction = async () => {
  // 发射事件通知其他组件
  proxy.$bus.emit('show-task-log');

  // 模拟一个异步函数
  await new Promise(resolve => setTimeout(resolve, 1000));
};
</script>

Vue 3中,事件总线模式已被移除,官方建议使用外部实现事件触发器接口的库,如mitt实现组件间通信。以下是使用mittVue 3实现组件间通信的方法: ### 安装mitt 可以使用以下几种包管理工具进行安装: ```bash # 使用npm npm install --save mitt # 使用yarn yarn add mitt # 使用pnpm pnpm install mitt ``` ### 编写mitt工具文件 在项目中创建mitt工具文件,例如`mitt.js`: ```javascript // 引入mitt import mitt from &#39;mitt&#39;; // 调用mitt得到emitter,emitter能:绑定事件、触发事件 const emitter = mitt(); // 暴露emitter export default emitter; ``` ### 使用mitt进行组件间通信 #### 兄弟组件间通信 两个子组件都引入`mitt.js`文件。以下是示例代码: - **子组件child2** ```vue <template> <div> <h3>兄弟组件间传值</h3> <el-button type="primary" @click="sendMsg">发送flag</el-button> </div> </template> <script setup> import { ref } from &#39;vue&#39;; import $bus from &#39;../utils/mitt&#39;; const isRightClickVal = ref(false); const sendMsg = () => { console.log(&#39;通知兄弟组件&#39;); $bus.emit(&#39;flag&#39;, &#39;isRightClickVal&#39;); }; </script> ``` - **子组件child1** ```vue <template> <div> <!-- 可以在模板中使用msg --> <p>{{ msg }}</p> </div> </template> <script setup> import { ref } from &#39;vue&#39;; import $bus from &#39;../utils/mitt&#39;; // 接收兄弟组件child2的信息 let msg = ref(&#39;默认&#39;); $bus.on(&#39;flag&#39;, (val) => { msg.value = val; console.log(&#39;msg:&#39;, msg.value); }); </script> ``` #### 任意组件间通信 - **接收数据的组件**:提前绑定好事件(提前订阅消息)。例如在某个组件中接收消息: ```vue <script setup> import { onMounted } from &#39;vue&#39;; import $bus from &#39;../utils/mitt&#39;; onMounted(() => { $bus.on(&#39;customEvent&#39;, (data) => { // 处理接收到的数据 console.log(&#39;接收到的数据:&#39;, data); }); }); </script> ``` - **提供数据的组件**:在合适的时候触发事件(发布消息)。例如在另个组件中发送消息: ```vue <script setup> import { ref } from &#39;vue&#39;; import $bus from &#39;../utils/mitt&#39;; const sendData = () => { const data = { message: &#39;这是条消息&#39; }; $bus.emit(&#39;customEvent&#39;, data); }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值