javascript
安装mitt :npm i mitt -S
main.ts:
javascript
import mitt from 'mitt'
const Mit = mitt();
declare module 'vue' {
export interface ComponentCustomProperties{
$Bus:typeof Mit
}
}
app.config.globalProperties.$Bus=Mit
在A组件中使用
handlebars
<template>
<div>
<h1>我是A</h1>
<button @click="emit">emit</button>
</div>
</template>
<script setup lang='ts'>
import {getCurrentInstance } from "vue";
const instance=getCurrentInstance();
const emit= ()=>{
instance?.proxy?.$Bus.emit("on-xiaoman","你是个小可爱")
}
</script>
<style>
</style>
在B组件中使用:
handlebars
<template>
<div>
<h1>我是B</h1>
</div>
</template>
<script setup lang='ts'>
import {getCurrentInstance } from "vue";
const instance=getCurrentInstance();
instance?.proxy?.$Bus.on('on-xiaoman',(str)=>{
console.log(str,'+++++++++B')
})
</script>
<style>
</style>
效果: