The introduction
The implementation of eventBus can simply be implemented directly with a Vue instance.
An introduction to
Listening, firing, and removing custom events on Vue component instances.
$on
$on itself is a function that binds a custom event to a component instance, which is emitted by $emit. The $ON function takes two arguments. The first parameter specifies the event name, and the second parameter specifies the callback function, which can accept any additional arguments passed by $emit. The first parameter has two types, a string to bind a single event and an array to bind multiple events simultaneously.
vue.$on('adList', (e) => {
console.log(e)
})
vue.$on(['adList1','adList2'], (e) => {
console.log(e)
})
Copy the code
$emit
$emit itself is a function that fires custom events bound to the component instance and passes additional arguments to the listener’s callback function. The first parameter of the $emit function is mandatory and specifies the event to fire. The remaining parameters are optional and are all parameters for the incoming event callback.
vue.$emit(event, [p1,p2,..] )Copy the code
$ON can bind multiple listeners to the same event, and when $EMIT fires the event, the listeners are executed in the binding order
Vue. $on (JPF, () = > {the console. The log (events' 1 ')}) vue. $on (' JPF '() = > {the console. The log (events' 2')}) vue. $emit (' JPF)Copy the code
$off
$off is itself a function that removes custom event listeners bound to component instances. The function takes two arguments, the first specifying the event to remove and the second specifying the callback function.
vue.$off([event, callback])
Copy the code
$off can be used in three ways
- If no arguments are provided, remove all event listeners on the current component instance.
- Second, if only the event name is provided, all listeners for that event are removed from the component instance.
- If both the event name and the callback function are provided, only listeners for the specified callback are removed from the specified event
The first argument to the $off function has two types
- A string used to remove a specified event
- A two-point array used to remove multiple specified events