Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In this article we will continue with Store options. In the last article we looked at actions and getters. Today we will talk about Modules.

Store options

Looking back at the state management section of Vue3 (1), we mentioned how to obtain Store in vex4.x.

Module

Because of the use of a single state tree, all the states of an application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated.

In our actual development, if the project is too large, there are too many modules, and more global states are needed, then we can use modules to separate modules for easy maintenance and reading.

const moduleA = {
  state: () = >({... }),mutations: {... },actions: {... },getters: {... }}const moduleB = {
  state: () = >({... }),mutations: {... },actions: {... }}const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA status
store.state.b // -> moduleB status
Copy the code

Each module has its own state, mutation, action, getter, and even nested submodules — split the same way from top to bottom, but the main thing we need is: Mutations and getters state of each module is a local state, and the context of actions of each module is also a local state, as follows:

const moduleA = {
  state: () = > ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // The 'state' object here is the local state of the module
      state.count++
    }
  },

  getters: {
    doubleCount (state,rootState) {
      return state.count * 2}}}Copy the code

It’s also important to note that modules’ getters and actions context have an extra parameter rootState to get the rootState.

conclusion

When your project is too large, using modules makes it easier to maintain and read. If you want your modules to be more wrapped and reusable, you can make them namespaced by adding Namespaced: True.

For more articles, the portal has opened: Look back at the Vue3 catalogue!