美文网首页react & vue & angular
vue3 中使用事件总线,实现兄弟组件传值

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

作者: 暴躁程序员 | 来源:发表于2023-04-17 22:59 被阅读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

相关文章

  • vue最全的组件通信和插槽,看这一篇就够了

    组件通信常用方式props父给子传值 自定义事件子给父传值$emit $bus事件总线任意两个组件之间传值常用事件...

  • angular组件之间的传值

    父子组件传值 父组件给子组件传值通过属性绑定的方式 子组件通过发送是事件给父组件传值 兄弟组件相互传值 兄弟组件通...

  • (VUE3) 四、组件传值(父子组件传值 & 祖孙组件传值 &v

    1.父子组件传值 vue2中的父子组件传值:父组件: 子组件: vue3中的父子组件传值: 还是用props接收父...

  • node的Event模块及js中自定义事件

    react中使用node的Event模块进行兄弟间的组件传值,事件使用的是发布-订阅模式

  • 前端VUE3,JQ,uniapp,综合

    vue3 + ts 子组件更新props 子组件可以直接修改父组件传进来的值子组件定义事件名称update:事件名...

  • VUE兄弟组件传值

    兄弟组件传值 创建一个实例,向这个实例上添加事件,然后在另外的实例中触发事件,即可实现传值 $on 添加事件 $e...

  • 组件传值之兄弟传值

    兄弟传值: 1、如果有共同的父组件,我们可以使用子传父,父传子 2、通过bus总线传值可以应用在任何情况的兄弟传值...

  • vue-eventbus

    eventbus就是事件总线,用来处理组件传值的一种方式,用法如下:

  • Vue组件通信

    父组件传值子组件 子组件传值父组件 非父子组件通信 发布订阅模式 / 总线模式 我们使用一个空的Vue实例作为总线...

  • vue.js 兄弟组件传值

    vue兄弟组件如何传值?兄弟组件如何相互操作组件里面的函数? 1、兄弟之间传递数据需要借助于事件车,通过事件车的方...

网友评论

    本文标题:vue3 中使用事件总线,实现兄弟组件传值

    本文链接:https://www.haomeiwen.com/subject/zifhjdtx.html