vue3 事件总线

在 Vue3 里官方已经不再提供 new Vue() 事件总线,可以使用mitt库替代,用法跟 Vue2 几乎一致

  • 安装 mitt
npm i mitt
  • 新建 src/utils/bus.js
import mitt from 'mitt'
const emitter = mitt()
export default emitter
  • 在组件里使用

    • 发送方 BrotherA.vue
    <template>
      <button @click="send">点我发消息</button>
    </template>
    
    <script setup>
    import emitter from '@/utils/bus'
    
    function send() {
      emitter.emit('foo', { msg: 'hello from BrotherA' })
    }
    </script>
    
    • 接收方 BrotherB.vue
    <template>
      <p>收到:{{ txt }}</p>
    </template>
    
    <script setup>
    import { onMounted, onUnmounted, ref } from 'vue'
    import emitter from '@/utils/bus'
    
    const txt = ref('')
    
    function handler(payload) {
      txt.value = payload.msg
    }
    
    onMounted(() => emitter.on('foo', handler))
    onUnmounted(() => emitter.off('foo', handler))   // 记得清理
    </script>
    

更多推荐