mitt
安装
pnpm add mitt
typescript
在 tsconfig.json 中设置 “strict”: true
{"compilerOptions": {"strict": true,}
}
使用
导出 emitter
src/utils/mitt/index.ts
import mitt from 'mitt'type Events = {'get-name': string
}export const emitter = mitt<Events>()
父组件
src/App.vue
<template><h1 @click="getName">Users App</h1>
</template><script setup lang="ts">
import { emitter } from '@/utils/mitt'function getName() {// 触发 get-name , 'zs' 传递的值emitter.emit('get-name', 'zs')
}
</script>
子组件
src/components/x-user/index.vue
<script lang="ts" setup>
import { emitter } from '@/utils/mitt'// name 接收的值
const handleChange = (name: string) => {console.log('🚀 ~ name:', name)
}// 监听 get-name 事件,
emitter.on('get-name', handleChange)// 停止监听 get-name 事件,
onBeforeUnmount(() => {emitter.off('get-name', handleChange)
})
</script>