美文网首页
eventbus事件总线

eventbus事件总线

作者: LuckySweet123 | 来源:发表于2021-03-25 12:09 被阅读0次

经常听说组件之间传参有一种方式是eventbus,常用于兄弟组件之间传参。但是我发现不只是兄弟之间可以用呀,为什么会被说“用与兄弟之间传参”呢?

1.首先来说说eventbus,字面意思有点“事件汽车”,有点大街上或者路边的快递小车车,谁需要寄件了找他,谁需要收件了会接到他的电话。

我们需要一辆小车车:

    // event-bus.js eventbus是一个不具备dom的组件
    import Vue from 'vue'
    export const EventBus = new Vue()

不推荐全局 这种 Vue.prototype.$bus = new Vue(),按需比较轻便

2.某个组件有内容要$emit发送出去,寄件

  //template中
  <button @click="sendMsg()">我是按钮</button>
  //script中
   import {EventBus} from "../../event-bus"
   // ...
   methods:{
    sendMsg(){
          EventBus.$emit('amsg','来自hello的消息')
      }
    }

3.另一个组件要接收内容,收件,保持手机畅通$on

  //created
  EventBus.$on('amsg',(msg)=>{
      this.msg=msg
  })
 // this.msg就拿到msg的值了

4.第一个组件里然后小车车腾空,走人,$off

  //beforeDestroy
  EventBus.$off('amsg',this.sendMsg)

太方便而容易滥用导致加大维护难度所以局限定位到了“常用于兄弟传参”?

相关文章

  • [Android组件解读] EventBus3.0解析

    记得前段时间讲解过otto事件总线的概念,但是大家习惯用的事件总线应该还是EventBus。 EventBus介绍...

  • eventBus源码解析

    EventBus定义:是一个发布 / 订阅的事件总线。 发布者,订阅者,事件,总线。 EventBus,可以说,就...

  • Vue的事件总线

    事件总线是什么? EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就...

  • EventBus和RxBus的使用

    EventBus介绍: Rx:函数响应式编程,EventBus:事件总线 。EventBus 功能类似handle...

  • vue 事件总线EventBus的概念、使用

    两个组件之间毫无关系,用到 vue 中的事件总线 EventBus的概念来传递数据 EventBus又称事件总线,...

  • 事件总线知多少(1)

    源码路径:Github-EventBus事件总线知多少(1)事件总线知多少(2) 1. 引言 事件总线这个概念对你...

  • Android小技巧之来不及解释了快上车--EventBus3

    什么是EventBus 先附上EventBus的git地址 EventBus,就按照名字翻译来说"事件总线",官方...

  • EventBus原理解析

    EventBus(发布订阅事件总线):通过解耦发布者和订阅者简化android 事件传递 EventBus is ...

  • 事件总线知多少(2)

    源码路径:Github-EventBus事件总线知多少(1)事件总线知多少(2) 1.引言 之前的一篇文章事件总线...

  • EventBus源码分析

    EventBus EventBus是一个为Android和Java平台设计的发布/订阅事件总线 EventBus有...

网友评论

      本文标题:eventbus事件总线

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