Vue3中事件总线模式已经被移除,官方建议使用外部库,例如mitt。
安装:
npm install --save mitt
首先main.ts挂载全局。
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import mitt from 'mitt'
const Mitt = mitt()
const app = createApp(App)
declare module 'vue' {
export interface ComponentCustomProperties {
$Bus: typeof Mitt
}
}
app.config.globalProperties.$Bus = Mitt
app.mount('#app')
A.vue中使用
<template>
<button @click="emitTip">emit点击</button>
</template>
<script setup lang="ts">
import { getCurrentInstance, ComponentInternalInstance } from 'vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const emitTip = ():void => {
proxy?.$Bus.emit('changeB', '我是你爸爸真伟大养你这么大')
}
</script>
<style lang="less" scoped>
</style>
B.vue接收
<template>
<div>
{{ str }}
</div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, ComponentInternalInstance } from 'vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
let str = ref<string>('')
proxy?.$Bus.on('changeB', (params: any)=> {
str.value = params
})
</script>
<style lang="less" scoped>
</style>