Search code examples
javascriptvue.jsvuex

Double nested dynamic module registration - vuex


According to the Vuex docs we can dynamically register a nested module in this way:

store.registerModule(['nested', 'myModule'], {
  // ...
})

And we can access this state using store.state.nested.myModule

How do I dynamically register a module nested another layer deep within the first module. IE. How can I make the modules exposed state be instead store.state.nested.furtherNested.myModule. Is this something that can be done?


Solution

  • You first need to register the furtherNested module:

    store.registerModule(['nested', 'furtherNested'], {
      // ...
    })
    

    And then register the myModule module in furtherNested by specifying the path in the array like so:

    store.registerModule(['nested', 'furtherNested', 'myModule'], {
      // ...
    })
    

    Here's a simple example:

    let store = new Vuex.Store({
      modules: { 
        nested: {}
      }
    });
    
    store.registerModule(['nested', 'furtherNested'], {})
    
    store.registerModule(['nested', 'furtherNested', 'myModule'], {
      state: { foo: 'bar' }
    })
    
    console.log(store.state.nested.furtherNested.myModule);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>