SoFunction
Updated on 2025-04-05

Detailed explanation of the use of Modules in vuex

Preface

In Vue, State uses a single state tree structure, and all states should be placed in the state. If the project is more complicated, then the state is a large object, and the store object will become very large and difficult to manage. So another core concept exists in Vuex. This article will summarize the relevant knowledge points of modules.

1. What are modules

Vuex allows us to split the store into modules, and each module has its own state, getters, mutation, action, etc., and even nested submodules - segmenting the store in the same way from top to bottom.

const moduleA = {
        state: () => ({ ... }),
        mutations: { ... },
        actions: { ... },
        getters: { ... }
    }
    const moduleB = {
        state: () => ({ ... }),
        mutations: { ... },
        actions: { ... }
    }
    const store = new ({
        modules: {
            a: moduleA,
            b: moduleB
        }
    })
     // -> Obtain moduleA status     // -> getmoduleB The status of

Internal state, the state inside the module is local, that is, the module is private.

The internal getter,mutation,action is still registered in the global namespace, which allows multiple modules to respond to the same mutation or action.

2. Internal parameters of module

For mutation and getter inside the module, the first parameter received is the local state object state of the module.

For actions inside the module, the local state is exposed through , and the root node state is :

For getters inside the module, the root node status will be exposed as the third parameter:

const moduleA = {
        state: () => ({
            count:"",
        }),
        actions: {
            //The state here is the local state, and rootState is the root node state            incrementIfOddOnRootSum ({ state, commit, rootState }) {
                if (( + ) % 2 === 1) {
                    commit('increment')
                }
            }
        }
        mutations: {
            // The `state` object here is the local state of the module            increment (state) {
                ++
            }
        },
        getters: {
            //The state here is the local state, and rootState is the root node state            doubleCount (state) {
                return  * 2
            },
            sumWithRootCount (state, getters, rootState) {
                return  + 
            }
        }
    }

3. Module namespace problem

(1) namespaced: true Make the module a module with namespace

When a module is registered, all its getters, actions and mutations will be automatically adjusted and named according to the path registered by the module.

const store = new ({
  modules: {
    account: {
      namespaced: true,
      // module assets When using module assets, there is no need to add additional space name prefix in the same module.      state: () => ({}), // The states in the module are already nested, using the `namespaced` property will not affect it      getters: {
        isAdmin() {}, // ->Usage: getters['account/isAdmin'],        // You can use the fourth parameter of getter to call        someGetter(state, getters, rootState, rootGetters) {
          // 
          // 
        },
      },
      actions: {
        login() {}, // ->Usage: dispatch('account/login')        // You can use the fourth parameter of action to call it        //If you need to distribute action or submit mutation in the global namespace, pass { root: true } as the third parameter to dispatch or commit        someAction({ dispatch, commit, getters, rootGetters }) {
          // ;
          // ;
          // dispatch("someOtherAction");
          // dispatch("someOtherAction", null, { root: true });
          // commit("someMutation");
          // commit("someMutation", null, { root: true });
        },
        someOtherAction(ctx, payload) {},
        // If you need to register a global action in a module with namespace, you can add root: true and place the definition of this action in the function handler.        otherAction: {
          root: true,
          handler(namespacedContext, payload) {}, // -> 'someAction'
        },
      },
      mutations: {
        login() {}, // ->Use: commit('account/login')      },
      // Nested modules      modules: {
        // Inherit the namespace of the parent module        myPage: {
          state: () => ({}),
          getters: {
            profile() {}, // -> Use:getters['account/profile']          },
        },

        // Further nesting namespaces        posts: {
          namespaced: true,

          state: () => ({}),
          getters: {
            popular() {}, // -> Use:getters['account/posts/popular']          },
        },
      },
    },
  },
});

(2) Use of binding functions with namespace

When using mapState, mapGetters, mapActions and mapMutations functions to bind modules with namespaces, it may be cumbersome to write:

computed: {
            ...mapState({
                a: state => ,
                b: state => 
            })
        },
        methods: {
            ...mapActions([
                'some/nested/module/foo', // -> this['some/nested/module/foo']()
                'some/nested/module/bar' // -> this['some/nested/module/bar']()
            ])
        }

createNamespacedHelpers Creates a namespace helper function based on a namespace, which returns an object with a new component bound helper function bound to a given namespace value.

import { createNamespacedHelpers } from 'vuex'
        const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
        export default {
            computed: {
                // Find in `some/nested/module`                ...mapState({
                a: state => ,
                b: state => 
                })
            },
            methods: {
                // Find in `some/nested/module`                ...mapActions([
                    'foo',
                    'bar'
                ])
            }
        }

4. Dynamic module registration

After the store is created, you can use the method to register the module

import Vuex from 'vuex'
        const store = new ({ /* Options */ })
        // Register module `myModule`        ('myModule', {
            // ...
        })
        // Register nested module `nested/myModule`        (['nested', 'myModule'], {
            // ...
        })

The module's status can then be accessed through and through.

You can also use (moduleName) to dynamically uninstall modules. Note that you cannot uninstall static modules (i.e. modules declared when the store is created).

You can check whether the module has been registered in the store through the (moduleName) method.

Written at the end

This is the end of this article about the detailed explanation of the use of Modules in vuex. For more related vuex Modules, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!