在 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
相关推荐
shinelord明14 小时前
【计算机网络架构】环型架构简介
计算机网络·架构·计算机科学·通信·计算机技术
梁辰兴14 小时前
企业培训笔记:宠物信息管理--实现宠物信息分页查询
笔记·elementui·mybatis·vue3·springboot·宠物
爱看书的小沐2 天前
【小沐杂货铺】基于Three.JS绘制汽车展示Car(WebGL、vue、react、autoshow、提供全部源代码)
汽车·vue3·react·webgl·three.js·opengl·autoshow
梁辰兴4 天前
企业培训笔记:Vue3前端框架配置
笔记·前端框架·npm·vue·vue3·node
知识分享小能手6 天前
Vue3 学习教程,从入门到精通,使用 VSCode 开发 Vue3 的详细指南(3)
前端·javascript·vue.js·学习·前端框架·vue·vue3
雪碧聊技术7 天前
v-for的用法及案例
vue3·uniapp·v-for·购物车案例
liulilittle8 天前
SNIProxy 轻量级匿名CDN代理架构与实现
开发语言·网络·c++·网关·架构·cdn·通信
liulilittle9 天前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
liulilittle10 天前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
所念皆星海91110 天前
图灵完备之路(数电学习三分钟)----数据选择器与总线
嵌入式硬件·通信·数电