vue3 使用 mitt 插件实现非父子组件传值

介绍 : mitt 是一个 JavaScript 库,用于实现事件的订阅和发布

1、安装

bash 复制代码
npm install mitt -S

2、新建 utils/eventBus.ts 文件

ts 复制代码
// eventBus.ts 文件

import mitt from 'mitt'
const eventBus = mitt()
export default eventBus

3、使用

vue 复制代码
// 组件1
<template>
  <div>
  <p>组件1: {{ message }}</p>
  <button @click="offGetMessageFn">关闭指定事件</button>
  <button @click="clearAllFn">清除所有自定义事件</button>
 </div>
<template>

<script lang="ts" setup>
import eventBus from '@/utils/eventBus'
const message = ref<string>('')
// 监听事件 getMesage
eventBus.on('getMessage', (msg: string) => {
  message.value = msg
})

// 关闭 getMesage 事件
const offGetMessageFn = () => {
 eventBus.off('getMessage')
}

// 清除所有自定义事件
const clearAllFn = () => {
 eventBus.all.clear()
}
</script>





// 组件2
<template>
  <div>
    <button @click="onClick">组件2: </button>
  </div>
<template>

<script lang="ts" setup>
import eventBus from '@/utils/eventBus'

// 发送事件
const onClick = () => {
  eventBus.emit('getMessage', 'hello 我是组件2发来的信息')
}
</script>
相关推荐
拉拉尼亚几秒前
WebRTC 完全指南:原理、教程与应用场景
前端·typescript·实时音视频
lkbhua莱克瓦242 分钟前
ZogginWeb 电脑端沉浸式记单词整合优化方案(终极版)
前端·zogginweb开发
小则又沐风a3 分钟前
深剖string内部结构 手撕string
java·前端·数据库·c++
不恋水的雨5 分钟前
html中补齐table表格合并导致每行td数量不一致的情况
前端·html
iReachers8 分钟前
HTML打包EXE工具四种弹窗方式图文详解 - 单窗口/新窗口/标签页/浏览器打开
前端·javascript·html·弹窗·html打包exe·html转程序
编程小风筝8 分钟前
就业信息推荐系统 Python+Django+Vue.js
vue.js·python·django
木斯佳16 分钟前
前端八股文面经大全:京东零售JDY前端一面(2026-04-14)·面经深度解析
前端·算法·设计模式·ai·断点续传
耗子君QAQ17 分钟前
🔧 Rattail | 面向 Vite+ 和 AI Agent 的前端工具链
前端·javascript·vue.js
Bigger18 分钟前
面试官问我:“AI 写代码比你快 100 倍,你的价值在哪?”
前端·面试·ai编程
恋恋风尘hhh2 小时前
滑动验证码前端安全研究:以顶象(dingxiang-inc)为例
前端·安全