vue3全局事件总线

1.安装mitt

npm install mitt -s

2.在main.js中引入

import mitt from "mitt";

3.全局配置

const app = createApp(App)
app.mount('#app')
app.config.globalProperties.mittBus = new mitt()

vue3全局事件总线_第1张图片

4.在需要提供数据的组件中引入

import {getCurrentInstance,reactive, toRefs} from "vue";

5.提供数据

const { proxy } = getCurrentInstance()
proxy.mittBus.emit('mittFn',{name: formInline.username})

6.在需要接收参数的组件中引入

import {getCurrentInstance, onMounted, reactive, toRefs,} from "vue";

7.接收数据

const { proxy } =getCurrentInstance()
onMounted(()=>{
    proxy.mittBus.on('mittFn',(data) =>{
        state.name = data.name
    })
})
onUnmounted(()=>{
    proxy.mittBus.off('mittFn')
})

你可能感兴趣的:(vue)