Read this in other languages: 简体中文 English
- Optional
strict
mode, only accept predefinedevents
- Auto remove event listeners (include anonymous function) in Vue beforeDestroy hook
- Event param can be
string | string[]
, on/off/fire multiple events - Bind
this
to target Vue component
npm install --save @shuzhong/vue-event-bus
commonjs
var VueEventBus = require('@shuzhong/vue-event-bus')
Vue.use(VueEventBus) // default options
// or
Vue.use(VueEventBus, {
events: ['EVENT-NAME-1', 'EVENT-NAME-2', 'EVENT-NAME-3'],
strict: true
})
ES2015+
import VueEventBus from '@shuzhong/vue-event-bus'
Vue.use(VueEventBus) // default options
// or
Vue.use(VueEventBus, {
events: ['EVENT-NAME-1', 'EVENT-NAME-2', 'EVENT-NAME-3'],
strict: true
})
External
<script type="text/javascript" src="your-folder-path/vue-event-bus.min.js"></script>
<script type="text/javascript">
Vue.use(VueEventBus) // default options
// or
Vue.use(VueEventBus, {
events: ['EVENT-NAME-1', 'EVENT-NAME-2', 'EVENT-NAME-3'],
strict: true
})
</script>
CompOne.vue
// .............
mounted() {
// Because this bind to CompOne, The next 4 this points to the same context
this.$busOn('EVENT_1', () => { console.log(this, '11') }) // Bind by ES6 arrow function
this.$busOn('EVENT_2', function() { console.log(this, '12') }) // Bind by VueEventBus
this.$busOnce('EVENT_3', () => { console.log(this, '13') }) // Bind by ES6 arrow function
this.$busOn('EVENT_4', this.busOnFunc1) // Bind by Vue (Vue Methods auto bind this)
// listen multiple events
this.$busOn(['EVENT_1', 'EVENT_2', 'EVENT_3'], function() { })
},
beforeDestroy() {
this.$busOff('EVENT_4', this.busOnFunc1)
// Destory multiple events (Clear all listeners for this event when the second argument is not passed)
this.$busOff(['EVENT_1', 'EVENT_2', 'EVENT_3'])
},
methods: {
busOnFunc1() { console.log(this, '14') }
}
// ...........
CompTwo.vue
this.$busFire('EVENT_1', 'arg1', 'arg2', [1, 2, 3, 4])
// Trigger multiple events in sequence
this.$busFire(['EVENT_1', 'EVENT_2', 'EVENT_3', 'EVENT_4'])
this.$busFire(['EVENT_1', 'EVENT_2', 'EVENT_3', 'EVENT_4'], 'arg1', 'arg2', [1, 2, 3, 4])
type Options = {
strict: boolean
events: string[]
}
Vue.use(VueEventBus, options?: Options = { strict: false, events: [] })
options:
- strict: { type: boolean, default: false }
- events: { type: string[], default: [] }
When strict
is true
, only event declared in events
are legal. If an undeclared event is on/off/fire, an error is thrown.
this.$busOn(evTag: string | string[], evFunc: Function)
this.$busOnce(evTag: string | string[], evFunc: Function)
this.$busOff(evTag: string | string[], evFunc?: Function)
Clear all event listeners corresponding to evTag
when the evFunc
param is not passed.
this.$busFire(evTag: string | string[], ...args: any[])
MIT