How do you register your Vuex Modules?

karmablackshaw

KarmaBlackshaw

Posted on June 6, 2022

How do you register your Vuex Modules?

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

You can register modules in your Vuex store as follows:

import Vue from 'vue'
import Vuex from 'vuex'

// modules
import users from './users'
import posts from './posts'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    users,
    posts
  }
})

Enter fullscreen mode Exit fullscreen mode

This structure is good for smaller projects, but what if you have lots of modules? Large applications can have equally large number of modules. As you can imagine, the file will eventually get bloated.

What I usually do in my projects is create an auto import for my modules which then makes creating and using the modules in your app, a walk in the beach.

Your modules directory might look like this:

Image description

Now for the exciting part, how do you actually register all of this like a walk in the beach? Here's what I do:

// modules.js
import _kebabCase from 'lodash/kebabCase'

const files = require.context(
  // the directory of your modules
  './modules', 
  // whether to look deep into each folder or not
  false, 
  // regexp to know which files to look for
  /\.js$/
)

const modules = {}

files.keys().forEach(fileName => {
  // I decided all of my modules should be kebab, but you can change it if you want.
  const moduleName = _kebabCase(fileName.replace(/(\.\/|\.js)/g, ''))
  modules[moduleName] = files(fileName).default
})

export default modules

Enter fullscreen mode Exit fullscreen mode

And in your store, import the modules.js:

// index.js
import Vue from 'vue'
import Vuex from 'vuex'

import modules from './modules'

Vue.use(Vuex)

export default new Vuex.Store({
  modules
})

Enter fullscreen mode Exit fullscreen mode

And voila! You can now use your modules in the app without even manually importing them in your vuex store.

import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState('auth', {
      authUser: 'authUser'
    })
  }
}
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
karmablackshaw
KarmaBlackshaw

Posted on June 6, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related