Simple Flux architecture with Vue.js

Using EventBus in Vue.js for a simple flux architecture.

For a small app that only needs a simple state management pattern. I always use one component to hold the state of the app, a container. This act as a single source of truth for an app to refer to its states. Vue provides a mechanism to create a global event listener called EventBus which is a super simple way to mimic flux architecture.

Image from Vue official site

All you need is one module that exports Vue as EventBus like so

import Vue from 'vue'
export const EventBus = new Vue()

Then you can use it inside your container to listen to event from any component inside the app. I normally add the listener on created life cycle.

/*
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>

Then you can import EventBus into any of your components and you can triggers my-custom-event from anywhere without having to emit the event to that component’s parent and repeat the whole process in every component in between the component that triggers the change and the target container.

Here is what CustomButton could look like

<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>

That’s it. As your app gets larger, you might want to consider using Vuex especially if many containers shared certain states.

Cheers!
Like 233 likes
Tino Thamjarat
Share:

Join the conversation

This will be shown public
All comments are moderated

Get our stories delivered

From us to your inbox weekly.