zoukankan      html  css  js  c++  java
  • vue 组件间 8 大通讯方式 之三 eventBus

    五、eventBus

    eventBus 又称为事件总线,在vue中可以使用它来作为沟通桥梁的概念, 就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件, 所以组件都可以通知其他组件。

    缺点:eventBus也有不方便之处, 当项目较大,就容易造成难以维护的灾难

    在Vue的项目中怎么使用eventBus来实现组件之间的数据通信呢?具体通过下面几个步骤

    1. 初始化

    首先需要创建一个事件总线并将其导出, 以便其他模块可以使用或者监听它.

    // event-bus.js
    
    import Vue from 'vue'
    export const EventBus = new Vue()

    2. 发送事件

    假设你有两个组件: additionNum 和 showNum, 这两个组件可以是兄弟组件也可以是父子组件;这里我们以兄弟组件为例:

    <template>
      <div>
        <show-num-com></show-num-com>
        <addition-num-com></addition-num-com>
      </div>
    </template>
    
    <script>
    import showNumCom from './showNum.vue'
    import additionNumCom from './additionNum.vue'
    export default {
      components: { showNumCom, additionNumCom }
    }
    </script>
    // addtionNum.vue 中发送事件
    
    <template>
      <div>
        <button @click="additionHandle">+加法器</button>    
      </div>
    </template>
    
    <script>
    import {EventBus} from './event-bus.js'
    console.log(EventBus)
    export default {
      data(){
        return{
          num:1
        }
      },
    
      methods:{
        additionHandle(){
          EventBus.$emit('addition', {
            num:this.num++
          })
        }
      }
    }
    </script>

    3. 接收事件

    // showNum.vue 中接收事件
    
    <template>
      <div>计算和: {{count}}</div>
    </template>
    
    <script>
    import { EventBus } from './event-bus.js'
    export default {
      data() {
        return {
          count: 0
        }
      },
    
      mounted() {
        EventBus.$on('addition', param => {
          this.count = this.count + param.num;
        })
      }
    }
    </script>

    4. 移除事件监听者

    import { eventBus } from 'event-bus.js'
    EventBus.$off('addition', {})
  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/benbonben/p/14958439.html
Copyright © 2011-2022 走看看