关于vue.js:vue-事件总线EventBus介绍

1次阅读

共计 1715 个字符,预计需要花费 5 分钟才能阅读完成。

1. eventbus 的简介

eventbus 又称为事件总线, 在 vue 中能够应用 eventbus 来作为沟通桥梁的概念, 是所有组件所共有的事件核心. 能够向该核心注册发送事件或接管事件. 所以组件都能够高低平行地告诉其余组件

2. 如何应用 eventbus

(1) 初始化

首先须要创立事件总线并将其导出, 以便其余模块能够应用或者监听它, 有两种形式解决
第一种, 新建一个 js 文件, 比方 event-bus.js

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

实际上 eventbus 是一个不具备 dom 的组件
另外一种形式, 能够间接在我的项目中的 main.js 初始化 EventBus:

// main.js
Vue.prototype.$EventBus = new Vue()
// 留神这种形式初始化的 EventBus 是一个全局事件总线, 

(2) 发送事件

假如有两个 vue 页面须要通信, A 页面在按钮下面绑定了点击事件, 发送一则音讯, 告诉 B 页面

// A 页面
<template>
    <button @click="sendMsg()">-</button>
</template>

<script> import {EventBus} from "../event-bus.js";
export default {
  methods: {sendMsg() {EventBus.$emit("aMsg", '来自 A 页面的音讯');
    }
  }
}; </script>

接下来在 B 页面接管音讯

(3) 接管事件

<!-- IncrementCount.vue -->
<template>
  <p>{{msg}}</p>
</template>

<script> import {EventBus} from "../event-bus.js";
export default {data(){
    return {msg: ''}
  },
  mounted() {EventBus.$on("aMsg", (msg) => {
      // A 发送来的音讯
      this.msg = msg;
    });
  }
}; </script>

后面提过, 如果应用不善,eventBus 会是一个劫难, vue 是单页面利用, 如果你再某一个页面刷新之后, 与之相干的 eventbus 将会被移除, 这样会导致业务走不上来. 还有就是如果业务有重复操作的页面, eventBus 在监听的时候就会触发很屡次, 也是一个十分大的隐患. 这时候咱们须要好好解决 eventbus 在我的项目中的关系, 通常是在 vue 页面销毁的时候, 共事移除 eventbus 事件监听

移除事件监听

import {eventBus} from './event-bus.js'
EventBus.$off('aMsg', {})

你可是要 EventBus.$off(‘eqwe’)移除利用内所有对此某个事件的监听, 或者间接调用 EventBus.$off() 来移除所有事件频道. 不增加任何参数~~~~

3. 全局 eventbus

它的工作原理是公布 / 订阅办法, 通常称为 pub/sub
创立全局 EventBus

// 1. 创立 bus.js 文件   **src/service/bus.js**
const install = (Vue) => { 
    const Bus = new Vue({ 
        methods: {on (event, ...args) {this.$on(event, ...args); 
            }, 
            emit (event, callback) {this.$emit(event, callback); 
            }, 
            off (event, callback) {this.$off(event, callback); 
            } 
        } 
    }) 
    Vue.prototype.$bus = Bus; 
} 
export default install;

// **maix.js 文件中引入 **
import Bus from "@/service/bus"; 
Vue.use(Bus);


// ** 组件中应用 **
this.$bus.on('Config_forms',(data)=>{}) // 绑定事件
this.$bus.emit('Config_forms',data) // 触发该办法 this.$bus.off('Config_forms') // 解绑事件 
正文完
 0