[Vuejs]-Vuex dynamic module register shows object empty

0👍

First you have to make sure that this.name !== undefined then you can dynamically add the module to the store like this (according to the DOC and API Reference)

this.$store.registerModule(this.name, {
  namespaced: true,
  state: {
    some_items: []
  },
  getters: {
    items: state => state.some_items
  },
  actions: {
    someAction () {}
  },
  mutations: {}
})

And use it as you always do this.$store.dispatch('yourModule/someAction')

If you wish you can also update your store index.js like this in order to register modules that have been exported by default as object

myModule.js

const state = {}
const actions = {}
const getters = {}
const mutations = {}

const module = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

export default module

store index.js

As you can see below i only made a small changes to the reduce method

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

Vue.use(Vuex)

// Load store modules dynamically.

const requireContext = require.context('./modules', false, /.*\.js$/)

const modules = requireContext.keys()
  .map(file =>
    [file.replace(/(^.\/)|(\.js$)/g, ''), requireContext(file)]
  )
  .reduce((modules, [name, mod]) => {

    let module = mod.default || mod

    if (module.namespaced === undefined) {
      module.namespaced = true
    }

    return { ...modules, [name]: module }
  }, {})

export default new Vuex.Store({
  modules
})

Leave a comment