1.安装mitt:
npm install mitt -S
2.使用方法:
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
const Mit = mitt()
//TypeScript注册
// 由于必须要拓展ComponentCustomProperties类型才能获得类型提示
declare module "vue" {
export interface ComponentCustomProperties {
$Bus: typeof Mit
}
}
const app = createApp(App)
//Vue3挂载全局API
app.config.globalProperties.$Bus = Mit
app.mount('#app')
子组件组件:A.vue == > 派发 $emit
<template>
<div>
我是A组件
<button @click="emit">emit</button>
</div>
</template>
<script setup lang='ts'>
import {getCurrentInstance} from 'vue'
const instance = getCurrentInstance()
const emit = () => {
instance?.proxy?.$Bus.emit('on-click','hello world')
}
</script>
<style scoped>
</style>
子组件组件:B.vue == > 监听 $on
<template>
<div>
我是B组件 ==> {{ getStr }}
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import { getCurrentInstance } from 'vue'
const getStr = ref<unknown>('');
const instance = getCurrentInstance()
instance?.proxy?.$Bus.on('on-click', (str) => {
console.log(str)
getStr.value = str
})
</script>
<style scoped>
</style>
父页面:
<template>
<div>
<A />
<B />
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import A from './A.vue'
import B from './B.vue'
</script>
<style scoped>
</style>
3.通过mitt传多条数据:
子组件组件:A.vue == > 派发多个
<template>
<div>
我是A组件
<button @click="emit">emit</button>
</div>
</template>
<script setup lang='ts'>
import {getCurrentInstance} from 'vue'
const instance = getCurrentInstance()
const emit = () => {
instance?.proxy?.$Bus.emit('on-click1','hello')
instance?.proxy?.$Bus.emit('on-click2','world')
}
</script>
<style scoped>
</style>
子组件组件:B.vue == > 监听多个 $on('*')
<template>
<div>
我是B组件 ==> {{ getStr1 }} - {{getStr2}}
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import { getCurrentInstance } from 'vue'
const getStr1 = ref<unknown>('');
const getStr2 = ref<unknown>('');
const instance = getCurrentInstance()
instance?.proxy?.$Bus.on('*', (type,str) => {
console.log(type,str)
if(type == 'on-click1'){
getStr1.value = str
}
if(type == 'on-click2'){
getStr2.value = str
}
})
</script>
<style scoped>
</style>
父页面:
<template>
<div>
<A />
<B />
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import A from './A.vue'
import B from './B.vue'
</script>
<style scoped>
</style>
移除监听事件(off)