在更大的 Vue.js 項(xiàng)目中,您可能會(huì)將事件總線抽象為單個(gè)文件,將其導(dǎo)入到需要使用的每個(gè)組件文件中。這樣,它不會(huì)污染全局命名空間。 或者,您可以通過(guò)向 Vue.js 原型,在默認(rèn)情況下將其提供給任何 Vue.js 組件 Object.defineProperty
// Create a global Event Bus
const EventBus = new Vue()
// Add to Vue properties by exposing a getter for $bus
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus;
}
}
}
允許Vue.js組件的事件總線:
// Emit an Event from a Component using the internal Event Bus
const ComponentWithEventBus = Vue.extend({
mounted: function(){
this.$bus.$emit('status', 'Component mounted')
this.$bus.$on('something', ()=>{
console.log("Something happened");
});
}
});