> In a larger Vue.js project, you would likely abstract the Event Bus into a single file, importing it into every component file where it needs to be used. This way, it does not pollute the global namespace.
Instead of having to import a file everywhere, I'm used to add the bus to the Vue prototype:
// Create a bus for global events
var busVue = new Vue()
// vue properties
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return busVue
}
}
}
so I can simply use it from any Vue component: this.$bus.$emit('error', 'Impossible to connect to the database')
for emitting, and for binding on: mounted: function (msg) {
this.$bus.$on('error', this.alert)
}