vue-bus-center
v0.0.2
Published
A simple event center for communications of components.
Downloads
2
Readme
vue-bus
vue-bus-center plugin is a event center for communications of components.
Install
npm install vue-bus
Usage
//In main.js
import Vue from 'vue'
import VueBus from 'vue-bus-center'
Vue.use(VueBus)
//In component example.vue
<template>
<div>
{{number}}
<button @click="handleAddRandom">Random Accumulate</button>
</div>
</template>
<script>
export default {
props: {
number: {
type: Number
}
},
methods: {
handleAddRandom() {
const num = Math.floor(Math.random() * 100 + 1)
// emit a 'add' event
this.$bus.emit('add', num)
}
}
}
</script>
//In example2.vue:
<template>
<div>
Random Accumulate
<Counter :number="number"></Counter>
</div>
</template>
<script>
import Counter from './counter'
export default {
components: {
Counter
},
data() {
return {
number: 0
}
},
methods: {
handleAddRandom(num) {
this.number += num
}
},
// listen a 'add' event from example.vue
// 'on' method must be used in created hook
created() {
this.$bus.on('add', this.handleAddRandom)
},
//Recommend to off a event in beforeDestroy hook
beforeDestroy() {
this.$bus.off('add', this.handleAddRandom)
}
}
</script>
API
$bus.on(event,callback)
event: String, a event name. callback: Function, callback for current event
$bus.off(event,callback)
event: String, a event name. callback: Function, callback for current event
$bus.emit('event'[,...args])
event: String, a event name. args: arguments which are sent to callback