在 Vue3 中使用 mitt 进行组件通信

npm 包地址

mitt 是一个轻量级的 JavaScript 事件触发器, 只有200b。有基本的事件触发、订阅和取消订阅功能,还支持用命名空间来进行更高级的事件处理。

功能特点:

  • Microscopic ------ weighs less than 200 bytes gzipped
  • Useful ------ a wildcard "*" event type listens to all events
  • Familiar ------ same names & ideas as Node's EventEmitter
  • Functional ------ methods don't rely on this
  • Great Name ------ somehow mitt wasn't taken

获取 mitt

你可以通过以下几种方式获取 mitt

  • 使用 NPM 包

首先,你需要在项目根目录下使用以下命令安装 mitt

bash 复制代码
# 使用 pnpm 安装
pnpm add mitt
# 使用 npm 安装
npm install --save mitt
# 使用 yarn 安装
yarn add mitt
  • 使用 CDN

你还可以通过 CDN 获取构建好的 mitt 文件。将以下代码添加到 HTML 文件的 <script> 标签中:

html 复制代码
<script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>

引入 mitt

  • 通过 NPM 包引入

JavaScript 文件顶部使用 import 引入 mitt

js 复制代码
// using ES6 modules
import mitt from 'mitt'

// using CommonJS modules
var mitt = require('mitt')
  • 使用 script 标签引入

通过直接在 HTML 文件中添加 <script> 标签,引入构建好的 mitt 文件:

html 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <!-- 引入 mitt 文件 -->
    <script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>
  </head>
</html>

使用 window.mitt 来调用方法。

组件中使用

以实时获取未读消息数量为例。

  1. 首先,新建一个 mitt.js 文件
js 复制代码
import mitt from 'mitt'

const emitter = mitt()

export default emitter
  1. 使用 on 订阅事件/ off 取消订阅
js 复制代码
import { onMounted, onUnmounted, ref } from 'vue'
import emitter from '@/utils/mitt'

const count = ref(0)

const readmessage = () => {
  count.value = count.value - 1
}
onMounted(() => {
  emitter.on('messageread', readmessage)
  ...
})
onUnmounted(() => {
  emitter.off('messageread', readmessage)
})
  1. 使用 emit 触发事件
js 复制代码
import emitter from '@/utils/mitt'

...
emitter.emit('messageread')
...

点击查看后,未读消息数量减一。

API

on

注册事件处理器

参数 类型 说明
type string | symbol Type of event to listen for, or '*' for all events
handler Function? Function to call in response to given event

off

移除事件处理器

参数 类型 说明
type string | symbol Type of event to unregister handler from, or '*'
handler Function? Handler function to remove

emit

触发事件,可以带参数,参数可以为任意类型值

参数 类型 说明
type string | symbol The event type to invoke
handler Any? Any value (object is recommended and powerful), passed to each handler
相关推荐
无名3872 小时前
Kamailio registrar 模块 aor 大小写的问题
通信
liulilittle19 小时前
XDP VNP虚拟以太网关(章节:一)
linux·服务器·开发语言·网络·c++·通信·xdp
liulilittle21 小时前
OPENPPP2 Code Analysis Two
网络·c++·网络协议·信息与通信·通信
Cherry的跨界思维1 天前
【AI测试全栈:Vue核心】19、Vue3+ECharts实战:构建AI测试可视化仪表盘全攻略
前端·人工智能·python·echarts·vue3·ai全栈·ai测试全栈
liulilittle1 天前
XDP VNP虚拟以太网关(章节:三)
网络·c++·网络协议·信息与通信·通信·xdp
liulilittle1 天前
XDP VNP虚拟以太网关(章节:二)
linux·服务器·网络·c++·通信·xdp
Misha韩3 天前
vue3 实时通讯 SSE
vue3·sse·实时通讯
冥界摄政王6 天前
Cesium学习第二章 camera 相机
node.js·html·vue3·js·cesium
无名3877 天前
关于 RTP/AVPF 的简单讨论
通信
Irene19917 天前
在 Vue3 中使用 Element Plus
vue3·element plus