SoFunction
Updated on 2025-04-07

Detailed explanation of how to elegantly manage Vue status

This article will focus on the following advanced usage aspects:

  • Helper functions: Simplifies a set of tool functions provided by using Vuex operations in Vue components.
  • Calculate properties: Use getters to encapsulate complex logic to make component logic clearer.
  • Namespace: Detailed explanation of the role and usage of namespaces to avoid naming conflicts between modules.
  • Modular: Split the state logic of Vuex into multiple modules and realize communication and collaboration between modules.

By studying this article, you will further master the advanced usage of Vuex, improve your understanding and application ability of Vuex, and organize your status management tree more elegantly!

1. Use Vuex helper functions

Vuex helper functions are a set of tool functions provided to simplify the operation of using Vuex in Vue components. Use helper functions to simplify access to states, getters, mutations, and actions, reducing redundant code and complex syntax.

Here are the common Vuex helper functions:

  • mapState: Simplified state mapping
  • mapGetters: Simplify getters mapping
  • mapMutations: Simplify mutations mapping
  • mapActions: Simplify actions mapping

1. mapState

mapStateFunctions are used to map states in the store to computed properties of a component, or to directly access these state properties. It accepts an array or object as an argument to specify the state property name to map.

Example:

import { mapState } from 'vuex'
export default {
  computed {
    ...mapState(['count'])
  },  
  mounted () {
    ()
  },
}

countThe corresponding is the state property in the Vuex store, by usingmapStatefunction,countAttributes are mapped to the component's computed properties and can be usedthisThe instance is directly obtained

2. mapGetters

mapGettersFunctions are used to map getters in the store to computed properties of a component, or to access these getters directly. It accepts an array or object as an argument to specify the getters function name to map.

Example:

import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["count"]),
  },
};

countThe corresponding one is the getter function in the Vuex store, by usingmapGettersfunction,countFunctions are mapped to the computed properties of the component.

3. mapMutations

mapMutationsFunctions are used to map mutations in the store to a component's method so that the component can call directlycommitto trigger mutations. It accepts an array or object as an argument to specify the name of the mutations function to be mapped.

Example:

import { mapMutations } from "vuex";
export default {
  methods: {
    ...mapMutations(["increment"]),
  },
};

incrementThe corresponding one is the mutation function in the Vuex store, by usingmapMutationsfunction,incrementFunctions are mapped into components' methods.

4. mapActions

mapActionsFunctions are used to map actions in the store to a component's method so that the component can call directlydispatchto trigger actions. It accepts an array or object as an argument to specify the name of the actions function to be mapped.

Example:

import { mapActions } from "vuex";
export default {
  methods: {
    ...mapActions(["incrementAsync"]),
  },
};

incrementAsyncThe corresponding one is the action function in the Vuex store, by usingmapActionsFunction, we willincrementAsyncFunctions are mapped into components' methods.

The use of Vuex helper functions can simplify the call and use of Vuex in components, making the code more concise and readable. By using these helper functions, we can more easily access and manipulate states, getters, mutations, and actions in the store.

2. Use getters to calculate attributes

1. The role of getters

In Vuex, getters are computed properties used to obtain states, similar to computed properties in components. They can process, filter or combine states in Vuex and provide new derived states in a responsive manner.

The purpose of getters is to get data from the store and display or use it in a processed form. Using getters in a component makes it easy to get the required state without repeatedly writing logic inside the component.

2. Use steps for getters

Definition getters

In Vuex module configuration, you can usegettersField definition getters.

const store = new ({
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: {
    computedState: state => {
      // Process state and return the calculated attributes of the derived state      return  + 10
    },
    filteredData: state => {
      // Filter the data in state according to the conditions and return the derived state      return (item =>  === true)
    }
  }
})

We define two getters above, namelycomputedStateandfilteredData

Use getters

Can be used in componentsmapGettersHelper functions or use$To access the value of getters.

import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['computedState', 'filteredData'])
  },
  mounted() {
    () // Output the processed state value    () // Output filtered data array    (this.$) // Access via $  }
}

In the above code, we usemapGettersHelper functions map getters to component's computed properties, which can then be used directly in the component.

3. The advantages of getters

Vuex getters have the following advantages in state management:

  • Unified management of computational properties: Sometimes some complex calculations are required based on some state values, such as filtering, combining, and transforming states, and getters allows us to manage these computed properties in a unified manner. By placing the computational logic in getters, the code can be made more maintainable and readable.

  • Responsive updates: Vuex's getters are responsive, and getters will automatically recalculate when the dependency state changes. This means that when the state that getters depends on changes, the relevant components will also be automatically updated. This avoids manual listening for changes in states or manually triggering updates of computed properties.

  • Avoid repeated calculations: Vuex optimizes getters cache. Getters will only be recalculated if the state on which getters depends changes. This avoids unnecessary computational overhead. Also, if the value of getters does not change, multiple accesses will be read directly from the cache. This can improve performance in some cases.

  • Encapsulation of complex logic: Sometimes, the processing logic between certain states may be more complicated, involving the interaction between multiple modules or multiple states. By using getters, these complex logic can be encapsulated into a single place, making component logic clearer and reducing code redundancy and duplication.

Vuex getters play a role in unified management of computing attributes, implementing responsive updates, avoiding repeated calculations, encapsulating complex logic, and improving reusability and testability in state management. They provide developers with a convenient and powerful way to handle and display state, making application state management more concise, maintainable and efficient.

3. Namespace

1. What is a namespace

In Vuex, namespaces are a way to organize and isolate modules to avoid naming conflicts between modules.

The namespace provides a hierarchical root for each module, so that the state, behavior, and getter of the module can be accessed through the namespace. This allows you to prefix the module's path to ensure that all the contents of the module are unique and do not conflict with other modules.

2. How to use namespaces

  • Define the namespace:

In a module, it can be set by setting it in the module configurationnamespaced: trueto define the namespace. For example:

const store = new ({
  modules: {
    myModule: {
      namespaced: true,
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
  }
})

The above code is calledmyModuleThe module is set as a namespace module.

  • Use namespace:

When using a namespace, you can refer to the module's state, behavior, and getter by adding a namespace prefix before accessing the contents of the module. For example:

// Access the status of the namespace module;
// Call the namespace module's mutation("myModule/mutationName", payload);
// Call the namespace module action("myModule/actionName", payload);
// Get the getter for the namespace block["myModule/getterName"];

As shown above, we use namespace prefixmyModule/to access and call module state, behavior, and getters.

The use of namespaces makes the relationship between modules clearer and avoids naming conflicts. butPlease note: Be careful when using namespaces to ensure that the contents of the module are correctly referenced and called.

IV. Modular management

1. Modular organizational structure

In Vuex, you can use a modular organizational structure to manage large state management. Modularity can divide the state of the entire application into multiple small modules, each with its own state, mutations, getters, and actions.

Here is the simplest modular organizational structure in Vuex:

├── 
├── 
├── components // Components└── store
    ├──          # Assemble the module and export the store's main file    └── modules
        ├──    # moduleA module        └──    # moduleB Module

(1) Define moduleA module

// Create a module Aconst moduleA = {
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      ++;
    },
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit("increment");
      }, 1000);
    },
  },
  getters: {
    doubleCount(state) {
      return  * 2;
    },
  },
};
export default moduleA;

(3) Introduce the used modules and create a Vuex instance

import Vue from "vue";
import Vuex from "vuex";
import moduleA from "moduleA";
import moduleB from "moduleB";
(Vuex);
// Create Vuex instanceconst store = new ({
  modules: {
    moduleA,
    moduleB,
  },
});
export default store;

In the above example, we define two modules: moduleA and moduleB. Each module has its own state, mutations, actions and getters. When creating Vuex instances, put these module objects inmodulesin option.

When using modular states in components, helper functions can be usedmapStatemapMutationsmapActionsandmapGettersTo simplify use:

import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
export default {
  computed: {
    ...mapState("moduleA", {
      countA: "count",
    }),
    ...mapState("moduleB", {
      nameB: "name",
    }),
    ...mapGetters("moduleA", ["doubleCount"]),
  },
  methods: {
    ...mapMutations("moduleA", ["increment"]),
    ...mapActions("moduleA", ["incrementAsync"]),
    ...mapMutations("moduleB", ["changeName"]),
  },
};

In the above example, by specifying the module name, we can map the state and operations in the module into the computed properties and methods of the component. passmapStateYou can use the module AcountMap ascountACompute attributes, byMutationsandmapActionsYou can use the module AincrementandincrementAsyncMethods that map to components.

Through a modular organizational structure, the state of large applications can be better managed and maintained, making the state structure clearer and maintainable. Modularity can also facilitate reuse of modules, split the modules into multiple files for management, and improve development efficiency.

Note: In the mutations and getters inside the module, you can userootStateandrootGettersParameters to access states and getters in the root module. For example, you can use it in the mutations of moduleAto get the name status in moduleB.

2. Advantages of using modularity

  • Code separation and organization: Split Vuex's state logic into multiple modules, which can better organize the code and improve the maintainability and readability of the code. Each module has its own state, operation and acquirer, making the code clearer and more extensible.

  • Avoid naming conflicts: Using modularity can avoid naming conflicts in global state. Each module has its own namespace to prevent naming conflicts between different modules and improves the robustness and stability of the code.

  • Improve reusability: The modular design allows modules to be reused in different applications. Common state modules can be encapsulated into separate modules, and then introduced and used in different applications.

  • Independent module debugging: Each module can independently modify and operate states, making it easy to debug. Through modularity, you can more accurately locate the problem and quickly resolve bugs.

3. Under what circumstances do you need to use modularity?

  • Large-scale applications: For large applications, using modularity can better organize and manage state. Different modules can be responsible for handling different business logics separately to make the code clearer.

  • Multiple-person collaborative development: In projects developed by multiple people, using modularity can better divide the work and cooperate. Each developer can be responsible for the development and maintenance of one or more modules, reducing code conflicts and impact ranges and improving development efficiency.

  • Complex business logic: For complex business logic, modularity can be used to split it into multiple independent modules, making the code easier to understand and maintain. Each module is responsible for handling its own logic, reducing the degree of coupling.

  • Reusable modules: If there is some common state logic that needs to be reused in different applications, it can be encapsulated into independent modules. This can avoid repeated writing of code, improving development efficiency and maintainability of code.

Vuex's modular design makes the code clearer, more maintainable, and is conducive to collaborative development and reuse of state logic for multiple people. Using modularity can bring many benefits in large applications or when complex business logic is required.

Conclusion

In this article, we introduce advanced use of Vuex, including modularity, namespaces, and advanced options. Through these advanced techniques, we can better organize and manage Vuex's state management.

Modularity is a very important feature in Vuex. By splitting the state into multiple modules, we can better manage complex application states. This allows for more flexibility in scaling and configuring our state management. Namespaces can help us resolve naming conflicts between modules and provide clearer semantics.

By mastering these advanced techniques, we can better respond to complex state management needs and improve the maintainability and development efficiency of our applications.

The above is a detailed explanation of how to elegantly manage Vue's state. For more information about Vue's state management, please follow my other related articles!