vue3使用mitt实现组件通信

创建vue3项目

npm install -g @vue/cli

vue create myproject(项目名)

安装mitt

npm install --save mitt
全局绑定

在 main.js引入

import mitt from 'mitt';
app.config.globalProperties.mittBus = mitt()

<template>
    <button @click="submit">mitt</button>
    <B />
</template>
 
<script>
import { defineComponent, getCurrentInstance } from 'vue'
import B from './b.vue'
export default defineComponent({
    components: { B },
    setup() {
        console.log(getCurrentInstance());
        const { proxy } = getCurrentInstance()
        console.log('.', proxy)
        const submit = () => {
            // 抛出事件
            proxy.mittBus.emit('update', { name: '张三' })
        }
        return {
            submit,
        }
    },
})
</script>

使用    b.vue

<template>
    <div>
        姓名:{{name}}
    </div>
</template>
 
<script>
import {
    defineComponent,
    getCurrentInstance,
    reactive,
    toRefs,
    onMounted,
    onUnmounted
} from 'vue'
export default defineComponent({
    setup() {
        let { proxy } = getCurrentInstance()
        let state = reactive({
            name: '',
        })
        onMounted(() => {
            // 收到
            proxy.mittBus.on('update', (data) => {
                console.log('mitt收到参数', data)
                state.name = data.name
            })
        })
        onUnmounted(()=>{
            // 离开时销毁
            proxy.mittBus.off("update")
        })
 
        return {
            ...toRefs(state),
        }
    },
})
</script>

点击 a.vue的按钮 b.vue 监听收到数据 ,!

posted @ 2022-06-15 15:53  奶包迷了鹿  阅读(624)  评论(0编辑  收藏  举报