react & vue & angular

vue3 中使用事件总线,实现兄弟组件传值

2023-04-17  本文已影响0人  暴躁程序员

一、vue2 中使用事件总线,实现兄弟组件传值

  1. 在 main.js 中定义事件总线
new Vue({
  router,
  store,
  render: (h) => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this;
  },
}).$mount("#app");
  1. 在组件A中监听事件
mounted() {
    this.$bus.$on("getUserInfo", (data) => {console.log(data)});
},
destroyed() {
    this.$bus.$off("getUserInfo");
},
  1. 在组件B中触发事件
mounted() {
    setTimeout(() => {
        this.$bus.$emit("getUserInfo", { username: "alias", password: "123456" });
    }, 1000);
},

二、vue3 中使用事件总线,实现兄弟组件传值

在vue3中 $on、$off、$once 被移除,$emit 保留
解决方案:使用第三方库 mitt 代替 $on、$off、$once 实现兄弟组件传值

  1. 安装 mitt
npm install mitt -S
  1. 在 main.js 中把事件总线绑定到全局属性上
import mitt from 'mitt'
app.config.globalProperties.Bus = mitt()
  1. 在组件A中监听事件
<script setup>
import { getCurrentInstance, onUnmounted } from 'vue'
const { $bus } = getCurrentInstance().appContext.config.globalProperties

$bus.on('getUserInfo', (data) => console.log(data))

onUnmounted(() => {
  $bus.off('getUserInfo')
})
</script>
  1. 在组件B中触发事件
import { getCurrentInstance, onMounted } from 'vue';
const { $bus } = getCurrentInstance().appContext.config.globalProperties

onMounted(()=>{
  setTimeout(() => {
    $bus.emit("getUserInfo", { username: "alias", password: "123456" });
  }, 1000);
})
  1. 官方示例
import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten
上一篇 下一篇

猜你喜欢

热点阅读