SoFunction
Updated on 2025-04-04

State management mode of vue vuex

vuex is a state management mode designed specifically and can also be debugged using devtools.

Note: The examples and other codes in this article will use the syntax of es6.

Link

  1. vuex official Chinese website
  2. Simple mall implemented using vue and vuex, for reference only

What is vuex?

Quote the official website of vuex first:

Vuex is a state management model developed specifically for applications. It uses centralized storage to manage the state of all components of the application and ensures that the state changes in a predictable way with corresponding rules.

State management mode, centralized storage management, it sounds very high-end and quite scary. In my opinion, vuex is to store all the variables that need to be shared in one object, and then place this object in the top-level component for other components to use. Let’s put it this way, consider vue as a js file, component as a function, then vuex is a global variable, but this "global variable" contains some specific rules.

In the componentized development of vue, it is often encountered that the current component state needs to be passed to other components. When parent-child components communicate, we usually use props + emit. However, when the communication parties are not parent-child components or even have no correlation at all, or a state needs to be shared with multiple components, it will be very troublesome and the data will be quite difficult to maintain, which is very unfriendly to our development. vuex is very practical at this time, but after using vuex, it also brings more concepts and frameworks, so be cautious!

What is the content in vuex?

Talk is cheap,Show me the code. Let's first take a piece of code to get so many texts:

const store = new ({
  state: {
    name: 'weish',
    age: 22
  },
  getters: {
    personInfo(state) {
      return `My name is ${}, I am ${}`;
    }
  }
  mutations: {
    SET_AGE(state, age) {
      commit(age, age);
    }
  },
  actions: {
    nameAsyn({commit}) {
      setTimeout(() => {
        commit('SET_AGE', 18);
      }, 1000);
    }
  },
  modules: {
    a: modulesA
  }
}

This is the most basic and complete vuex code; vuex contains five basic objects:

  1. state: Store state. That is, variables;
  2. getters: derived state. That is, get in set and get, there are two optional parameters: state and getters that can obtain variables in state and other getters respectively. External call method: (). It's almost the same as vue's computed;
  3. mutations: Submit status modification. That is, set in set and get. This is the only way to modify state in vuex, but it does not support asynchronous operations. The first parameter is state by default. External call method: ('SET_AGE', 18). Similar to methods in vue.
  4. actions: Similar to mutations. However, actions support asynchronous operations. The first parameter is an object with the same parameter attribute as the store. External call method: ('nameAsyn').
  5. modules: the submodule of the store, the content is equivalent to an instance of the store. The call method is similar to the one introduced earlier, except that the current submodule name must be added, such as: ().

How to use vuex in vue-cli

Generally speaking, we will use vue-cli for actual development. In vue-cli, the development and call methods are slightly different.

├── 
├── 
├── components
└── store
  ├──      # Where we assemble the module and export the store  ├──      # and level state  ├──     # and level getter  ├──  # root level mutation name (officially recommended mutation method name is capitalized)  ├──    # root level mutation  ├──     # root level action  └── modules
    ├──      #Module 1    └──      # Module2

Example:

const state = {
  name: 'weish',
  age: 22
};

export default state;

Example (We generally use getters to get the state of the state instead of using the state directly):

export const name = (state) => {
  return ;
}

export const age = (state) => {
  return 
}

export const other = (state) => {
  return `My name is ${}, I am ${}.`;
}

Example (We will put all the function names of mutations in this file):

export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';

Example:

import * as types from './';

export default {
  [types.SET_NAME](state, name) {
     = name;
  },
  [types.SET_AGE](state, age) {
     = age;
  }
};

Example (when asynchronous operation, multiple commits):

import * as types from './';

export default {
  nameAsyn({commit}, {age, name}) {
    commit(types.SET_NAME, name);
    commit(types.SET_AGE, age);
  }
};

Example (If it is not a very complex application, it will not be divided into modules):

export default {
  state: {},
  getters: {},
  mutations: {},
  actions: {}
};

Example (assembly vuex):

import vue from 'vue';
import vuex from 'vuex';
import state from './';
import * as getters from './';
import mutations from './';
import actions from './';
import m1 from './modules/';
import m2 from './modules/';
import createLogger from 'vuex/dist/logger'; // Modify log
(vuex);

const debug = .NODE_ENV !== 'production'; // True in the development environment, otherwise it is false
export default new ({
  state,
  getters,
  mutations,
  actions,
  modules: {
    m1,
    m2
  },
  plugins: debug ? [createLogger()] : [] // Display vuex status modification in development environment});

Finally, just mount the store instance to the vue inside

import store from './store/';

new Vue({
 el: '#app',
 store,
 render: h => h(App)
});

When using in vue components, we usually use mapGetters, mapActions, mapMutations, and then we can call these variables or functions in the way vue calls methods and computed. The example is as follows:

import {mapGetters, mapMutations, mapActions} from 'vuex';

/* Write only the script part in the component */
export default {
  computed: {
    ...mapGetters([
      name,
      age
    ])
  },
  methods: {
    ...mapMutations({
      setName: 'SET_NAME',
      setAge: 'SET_AGE'
    }),
    ...mapActions([
      nameAsyn
    ])
  }
};

Summarize

The above is the relevant knowledge of vuex. In fact, vuex is very simple. You will become familiar with it after using it a few more times. The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.