Vuex can be used for this purpose. If a project does not need a library like Vuex to handle data communication between components, it can consider the EventBus in Vue, that is, EventBus.

Vue2. X implements EventBus

// event-bus.js
import Vue from 'vue'
export const EventBus = newVue () or// main.js
Vue.prototype.$EventBus = new Vue()
Copy the code

Since the vue instance provides $on, $emit, etc., you only need to create an empty vue instance, register the event through $on() in the component, execute the corresponding event through $emit() in the other component, and pass parameters to achieve communication between components.

Implement a simple EventBus

const eventBus = () = > {
  /* Subscriber */
  subs = new Map(a);return {
    subs,

    /** * Register event *@param {string} Type Indicates the event type *@param {Function} Callback function */
    $on (type, callback) {
      const sub = subs.get(type);
      const isEmpty = sub && sub.push(callback);
      if (!isEmpty) {
        subs.set(type, [callback]);
      }
    },

    /** * trigger event *@param {string} Type Indicates the event type *@param {Any} Payload Specifies the transmitted parameter */$emit (type, ... payload) { (subs.get(type) || []).forEach(fn= >{ fn(... payload) }); (subs.get(The '*') || []).forEach(fn= >{ fn(... payload) });/* All event types are executed */
    },
    
    /** * Logout event *@param {string} Type Indicates the event type *@param {Function} Callback function */
    $off (type, callback) {
      const sub = subs.get(type);
      if (sub) {
        sub.splice(sub.indexOf(callback) >>> 0.1); }}}}module.exports = eventBus
Copy the code

Subs subscribers can be implemented using objects or maps, which have their own clear method to clear all registered events

subs = new Map();
Copy the code

$on events registered with the same type will be pushed into the same array. $on events registered with the same type will be pushed into the same array. $on events registered with the same type will be pushed into the same array. When calling $emit, find the corresponding type loop array and execute all of its callback functions.

use

const eventBus = require('./eventBus')
const emitter = eventBus()

// Register the change event
emitter.$on('change'.(. payload) = > {
  console.log('change'. payload) })// This method is executed when all events are called
emitter.$on(The '*'.(. payload) = > {
  console.log('all'. payload) })// Trigger the change event
emitter.$emit('change'.Parameters' 1 '.Parameters' 2 ')
Copy the code

The results

You can use the Map clear to clear the EventBus

emitter.subs.clear() / / clear the EventBus
Copy the code