Search code examples
vue.jsvuexvuex-modules

Vuex access modules in subdirectories


I have the following directory structure:

  • store
    • modules
      • file1.js
      • file2.js
      • file3.js
      • anotherFolder
        • filex1.js

My question is, how to access the state of anotherFolder/filex1.js I can set the value, but I can't get it.

this.$store.dispatch('anotherFolder/filex1/myAction', {}) //work

let val = this.$store.state.anotherFolder.filex1.myValue //not work

I am importing the modules as follows.

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  getters
})

export default store

my filex1.js

export default {
    namespaced: true,
    state: {
      myValue: {}
    },
    actions: {
      myAction({ commit }, reg) {
        commit('MY_ACTION', reg)
      }
    },
    mutations: {
      MY_ACTION(state, reg) {
        state.myValue = reg
      }
    }
  }
  

I want to organize the store's files in subdirectories so I don't have everything in the modules folder. thanks!


Solution

  • you could use the binding helpers provided by vuex in your component to access the state in a nested module:

    computed: {
      ...mapState({
        a: state => state.some.nested.module.a,
        b: state => state.some.nested.module.b
      })
    

    }

    see: https://vuex.vuejs.org/guide/modules.html#namespacing