Bus
It's a wrapper of mitt a simple event emitter. To learn more about mitt, read the documentation on github
Composition Api
useBus
is a composable that provides an event bus for communication between components.
@param {string} channel - The name of the channel to use for the event bus. @returns {Object} An object containing the following methods:
on
: Registers an event listener for the specified event.off
: Unregisters an event listener for the specified event.emit
: Emits an event to all registered listeners.listeners
: Retrieves all registered listeners for the specified event.
vue
<script setup>
const num = ref(0)
const bus = useBus('<your-channel>')
bus.on(val => num.value = val)
function emitEvent() {
bus.emit(Math.random())
}
</script>
Legacy
vue
<script>
export default {
mounted() {
// start listening
this.$bus.on('<your-channel>', this.busListener)
},
beforeDestroy() {
// stop listening
this.$bus.off('<your-channel>', this.busListener)
},
methods: {
busListener(data) {
// do something with data
},
emitOnBus(data) {
// emit an event on the listeners
this.$bus.emit('<your-channel>', { ...data })
},
}
}
</script>
The two methods, on
and off
are used respectively to add/remove a listener for an event.
The method emit
is used to emit an event on the listeners.