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>
相关推荐
天宇&嘘月2 小时前
web第三次作业
前端·javascript·css
小王不会写code2 小时前
axios
前端·javascript·axios
发呆的薇薇°4 小时前
vue3 配置@根路径
前端·vue.js
luoluoal4 小时前
基于Spring Boot+Vue的宠物服务管理系统(源码+文档)
vue.js·spring boot·宠物
luckyext4 小时前
HBuilderX中,VUE生成随机数字,vue调用随机数函数
前端·javascript·vue.js·微信小程序·小程序
小小码农(找工作版)4 小时前
JavaScript 前端面试 4(作用域链、this)
前端·javascript·面试
前端没钱4 小时前
前端需要学习 Docker 吗?
前端·学习·docker
前端郭德纲4 小时前
前端自动化部署的极简方案
运维·前端·自动化
海绵宝宝_5 小时前
【HarmonyOS NEXT】获取正式应用签名证书的签名信息
android·前端·华为·harmonyos·鸿蒙·鸿蒙应用开发
码农土豆5 小时前
chrome V3插件开发,调用 chrome.action.setIcon,提示路径找不到
前端·chrome