Vue event bus

Originally there is an interaction between the data components directly related to his son, but not for direct between components, and how to interact with the data it

Providing a central global event, each component, like the built-in event stream as easy to use it as a global event and note

Working principle is to use publish / subscribe way

1. Create an event bus

Import View from 'for' 
export EventBus const = new View () 

Create a global event bus

// main.js 
Vue.prototype. EventBus $ = new View ()

2. Send a message

EventBus $ emit ( "aMsg", 'A page message from');. // A sends a message to B

3. monitor received messages

EventBus $ on. ( "AMsg" , (msg) => {// A message transmitted 
  this.msg = msg; // B A monitor the received data message is msg
});

4. Remove event

EventBus.$off('aMsg', {})

 

Create a EventBus, event bus project in Vue

var EventBus = new Vue (); // data bus event is a global property of the object prototype object 
 
Object.defineProperties (Vue.prototype, { 
  $ Bus: { 
    GET: function () { 
      return EventBus 
    } 
  } 
})
this $ bus $ emit ( 'nameOfEvent ', {... pass some event data ...});.. // prototypes call attributes and monitoring data transmission 
 
.. this $ bus $ on ( 'nameOfEvent', ($ Event) => { 
  // ... 
})

  

Guess you like

Origin www.cnblogs.com/panjingshuang/p/12096041.html