在 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
相关推荐
duansamve20 小时前
Vue3和vue2的Diff算法有何差异?
vue·vue3·vue2·diff
JNU freshman1 天前
Element Plus组件
前端·vue.js·vue3
liulilittle3 天前
国际带宽增长与用户体验下降的悖论
网络·网络协议·信息与通信·ip·ux·带宽·通信
Sheldon一蓑烟雨任平生4 天前
Vue3 列表渲染
vue.js·vue3·v-for·列表渲染·vue3 列表渲染·v-for 循环对象·v-for与计算属性
duansamve4 天前
TS在Vue3中的使用实例集合
typescript·vue3
ღ᭄ꦿ࿐Never say never꧂4 天前
微信小程序 Button 组件 open-type 完全指南:从用户信息获取到客服分享的实战应用
spring boot·微信小程序·小程序·uni-app·vue3
Sheldon一蓑烟雨任平生5 天前
Vue3 Class 与 Style 绑定
vue.js·vue3·class与style绑定·绑定class·绑定style·vue3绑定class·vue3绑定style
liulilittle10 天前
Linux 内核网络调优:单连接大带宽吞吐配置
linux·运维·服务器·网络·信息与通信·通信
liulilittle10 天前
Linux内核网络优化:两个网络调优解决方案
linux·运维·服务器·网络·内核·信息与通信·通信
昔冰_G14 天前
Vue内置组件KeepAlive——缓存组件实例
vue.js·缓存·vue3·vue2·keep-alive·vue组件缓存·vue内置组件