下载 Mitt 依赖:
npm install mitt -S
1、全局引入:
1、main.ts中引入
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
export const app = createApp(App)
const Mit = mitt()
declare module 'vue' {
export interface ComponentCustomProperties {
$Bus: typeof Mit
}
}
app.config.globalProperties.$Bus = Mit
app.mount('#app')
2、使用展示
(1)传递值
<template>
<div>
<h1>传递值组件</h1>
<div @click="emitClick">点击传递值</div>
</div>
</template>
<script setup lang="ts">
// 传递值组件
import { getCurrentInstance } from 'vue'
const Instance = getCurrentInstance()
const emitClick = () => {
Instance?.proxy?.$Bus.emit('emitData' , '传输过去的值')
}
</script>
(2)接收值(接收指定事件传递值)
<template>
<div>
<h1>接收值组件</h1>
</div>
</template>
<script setup lang="ts">
// 接收值组件 接收单个指定事件传递过来的值
import { getCurrentInstance } from 'vue';
const Instance = getCurrentInstance()
Instance?.proxy?.$Bus.on('emitData' , (value) => {
console.log(value , '接收传递过来的值')
})
</script>
(3)接收值(接收多个事件传递值)
<template>
<div>
<h1>接收值组件</h1>
</div>
</template>
<script setup lang="ts">
// 接收值组件 接收多个事件传递过来的值
import { getCurrentInstance } from 'vue';
const Instance = getCurrentInstance()
Instance?.proxy?.$Bus.on('*' , (type , value) => {
// type 为事件名称
// value 为每个事件对应的传递值
console.log(type , value , '接收多个事件传递过来的值')
})
</script>
(4)清除值 (清除所有和单个事件清除)
// 清除所有
instance?.proxy?.$Bus.all.clear()
// 清除指定传递事件
instance?.proxy?.$Bus.off('需要清除的事件名', (value) => {
console.log(value, '事件消除')
})
2、按需引入(推荐使用)
1、创建一个Bus.ts文件
import mitt from 'mitt'
const Mit = mitt()
export default Mit
2、传递值
<template>
<div>
<h1>传递值组件</h1>
<div @click="emitClick">点击传递值</div>
</div>
</template>
<script setup lang="ts">
// 传递值组件
import Mit from 'Bus文件路径'
const emitClick = () => {
Mit.emit('自定义事件名称' , '需要传递的值')
}
</script>
3、接收值
<template>
<div>
<h1>接收值组件</h1>
</div>
</template>
<script setup lang="ts">
// 接收值组件 接收多个事件传递过来的值
import Mit from 'Bus.ts文件路径'
// 接收指定事件传递的值
Mit.on('指定事件名称' , (value) => {
console.log(value)
})
// 接收所有的事件传递的值
Mit.on('*' , (type , value) => {
// type 为事件名称
// value 为每个事件对应的传递值
console.log(type , value , '接收多个事件传递过来的值')
})
</script>
4、清除传递值
// 清除所有
Mit.all.clear()
// 清除指定传递事件
Mit.off('需要清除的事件名', (value) => {
console.log(value, '事件消除')
})