Using EventBus in Vue.js for a simple flux architecture.
import Vue from 'vue'
export const EventBus = new Vue()
/*
In this scenario you could just use `vm.$emit` to communicate to `Container` from `CustomButton.
In reality, this pattern will shine when your component is nested inside some more components and
you can't really emit event to the `Container` quite easily.
*/
<template>
<custom-button label='Click me and the I will update the container state' />
</template>
<script>
import { EventBus } from "./EventBus.js"
import CustomButton from "./CustomButton.vue"
export default {
data () {
return { buttonClickCount: 0 }
},
created () {
EventBus.$on('my-custom-event', (params) => {
// you can submit data via params when emitting event.
console.log(params)
this.buttonClickCount++
}
},
components: {
'custom-button': CustomButton
}
}
</script>
<template>
<button @click='increaseUpdateCount'>{{label}}</button>
</template>
<script>
import { EventBus } from './EventBus.js'
export default {
props: ['label'],
methods: {
increaseUpdateCount () {
EventBus.$emit('my-custom-event', 'hello')
}
}
}
</script>
From us to your inbox weekly.