怀化老年网站,博物馆网站建设的目标,wordpress工具栏条,wordpress orchidv 插件npm 包地址
mitt 是一个轻量级的 JavaScript 事件触发器#xff0c; 只有200b。有基本的事件触发、订阅和取消订阅功能#xff0c;还支持用命名空间来进行更高级的事件处理。
功能特点#xff1a;
Microscopic —— weighs less than 200 bytes gzippedUseful —— a wil…npm 包地址
mitt 是一个轻量级的 JavaScript 事件触发器 只有200b。有基本的事件触发、订阅和取消订阅功能还支持用命名空间来进行更高级的事件处理。
功能特点
Microscopic —— weighs less than 200 bytes gzippedUseful —— a wildcard “*” event type listens to all eventsFamiliar —— same names ideas as Node’s EventEmitterFunctional —— methods don’t rely on thisGreat Name —— somehow mitt wasn’t taken
获取 mitt
你可以通过以下几种方式获取 mitt。
使用 NPM 包
首先你需要在项目根目录下使用以下命令安装 mitt
# 使用 pnpm 安装
pnpm add mitt
# 使用 npm 安装
npm install --save mitt
# 使用 yarn 安装
yarn add mitt使用 CDN
你还可以通过 CDN 获取构建好的 mitt 文件。将以下代码添加到 HTML 文件的 script 标签中
script srchttps://unpkg.com/mitt/dist/mitt.umd.js/script引入 mitt
通过 NPM 包引入
在 JavaScript 文件顶部使用 import 引入 mitt
// using ES6 modules
import mitt from mitt// using CommonJS modules
var mitt require(mitt)使用 script 标签引入
通过直接在 HTML 文件中添加 script 标签引入构建好的 mitt 文件
!DOCTYPE html
htmlheadmeta charsetutf-8 /!-- 引入 mitt 文件 --script srchttps://unpkg.com/mitt/dist/mitt.umd.js/script/head
/html使用 window.mitt 来调用方法。
组件中使用
以实时获取未读消息数量为例。
首先新建一个 mitt.js 文件
import mitt from mittconst emitter mitt()export default emitter使用 on 订阅事件/ off 取消订阅
import { onMounted, onUnmounted, ref } from vue
import emitter from /utils/mittconst count ref(0)const readmessage () {count.value count.value - 1
}
onMounted(() {emitter.on(messageread, readmessage)...
})
onUnmounted(() {emitter.off(messageread, readmessage)
})使用 emit 触发事件
import emitter from /utils/mitt...
emitter.emit(messageread)
...点击查看后未读消息数量减一。
API
on
注册事件处理器
参数类型说明typestring | symbolType of event to listen for, or ‘*’ for all eventshandlerFunction?Function to call in response to given event
off
移除事件处理器
参数类型说明typestring | symbolType of event to unregister handler from, or ‘*’handlerFunction?Handler function to remove
emit
触发事件可以带参数参数可以为任意类型值
参数类型说明typestring | symbolThe event type to invokehandlerAny?Any value (object is recommended and powerful), passed to each handler