vue3+ts mitt的使用

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>

效果:

相关推荐
小灰灰搞电子3 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
传奇开心果编程5 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
新时代牛马5 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob5 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
mayaairi5 小时前
Vue2 生命周期完全指南:从创建到销毁的8个钩子函数
前端·javascript·vue.js
研☆香6 小时前
一个简单的气泡弹窗制作
javascript
白山编程大哥6 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
大模型丫丫6 小时前
用 TypeScript、NestJS 和 LangGraph 搭建一个可控的 AI Agent
javascript·人工智能·typescript
IMPYLH6 小时前
HTML 的 <pre> 元素
前端·javascript·html
shmily麻瓜小菜鸡7 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript