在 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
相关推荐
无名3871 小时前
Kamailio usrloc 细节测试
通信
凯小默5 小时前
36-引入地图
echarts·vue3
xixixi7777711 小时前
App反诈骗:一场面向移动生态的深度安全战争(接上文短信反诈)
安全·信息与通信·通信·电话反诈
凯小默11 小时前
【TypeScript+Vue3+Vite+Vue-router+Vuex+Mock 进行 WEB 前端项目实战】学习笔记共 89 篇(完结)
typescript·echarts·mock·vue3·vite·vuex·vue-router
凯小默1 天前
34-监听数据渲染饼图以及饼图配置
vue3
凯小默2 天前
30-更新用户信息并且刷新表格
vue3
凯小默2 天前
27-编辑用户信息弹框组件化(显示隐藏功能)
vue3
凯小默2 天前
31-实现分配角色弹框(显示列表和选中当前用户的角色)
vue3
凯小默2 天前
29-定义用户对象类型(接口类型)
vue3
八目蛛3 天前
色盲测试小游戏
vue.js·vue3·html5