vue3 中使用mitt 兄弟组件通信(笔记)

147 阅读1分钟

安装mitt npm install mitt -s

这里我使用全局挂载方式 在mian.js文件中引入

import { createApp } from 'vue'  
import mitt from "mitt";  
import App from './App.vue'  
  
const Mit=new mitt()  
  
const app = createApp(App)  
  
app.config.globalProperties.$mitt=Mit  
  
app.mount('#app')

在B组件中发送信息

<template>  
<div class="home-container">  
<p>我是B组件</p>  
<button @click="sendMitt">$mitt发送数据</button>  
</div>  
</template>  
  
<script lang="ts" setup>  
import { getCurrentInstance, ref } from 'vue';  
  
  
const instance = getCurrentInstance();  
const num = ref<number>(0);  
  
const sendMitt = () => {  
instance.proxy.$mitt.emit('moneyEvent', ++num.value)  
}  
  
</script>  
  
<style lang="less">  
</style>

在A组件中接收

<template>  
<div class="container">  
<p>我是A组件</p>  
<p>接收到的数据:{{ num }}</p>  
</div>  
</template>  
  
<script lang="ts" setup>  
import { ref, getCurrentInstance, onBeforeMount, onMounted } from 'vue';  
  
const num = ref(0);  
const instance = getCurrentInstance();  
  
onMounted(() => {  
instance.proxy.$mitt.on('moneyEvent',(res)=>{  
num.value=res  
})  
})  
  
onBeforeMount(() => {  
instance.proxy.$mitt.off('moneyEvent')  
});  
  
</script>  
  
<style lang="less">  
  
</style>

app.vue

<template>  
  
<B></B>  
<A></A>  
</template>  
  
<script setup lang='ts'>  
  
import B from "./components/B.vue";  
import A from "./components/A.vue";  
  
</script>  
  
<style lang='less'>  
#app,  
html,  
body {  
height: 100%;  
}  
  
* {  
padding: 0;  
margin: 0;  
}  
</style>