在 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
相关推荐
陈逸子风5 小时前
从0到1搭建权限管理系统系列三 .net8 JWT创建Token并使用
vue3·webapi·权限·流程
一只小阿乐2 天前
前端web端项目运行的时候没有ip访问地址
vue.js·vue·vue3·web端
流氓也是种气质 _Cookie2 天前
13 vue3之内置组件keep-alive
vue3·keep-alive
Modify_QmQ3 天前
Three.js 实战【3】—— 城市模型渲染
3d·vue3·three·glbf
山水阳泉曲5 天前
开发后台管理系统-开发环境搭建
vue3·cdn·后台管理·从零开始
陈逸子风5 天前
.net core8 使用JWT鉴权(附当前源码)
vue3·webapi·权限·流程
小许_.8 天前
vite+vue3快速构建项目+router、vuex、scss安装
前端·css·vue3·vite·scss
行思理8 天前
UniApp 从Vue2升级为Vue3需要注意哪些方面
javascript·vue.js·uni-app·vue3·vue2
唯之为之11 天前
vue3项目部署到Github
vue·github·pnpm·vue3·vite
一雨方知深秋11 天前
vue3 项目中使用git
css·git·gitee·html·vue3