SoFunction
Updated on 2025-04-04

About Vuex 2.0 for 2.0 You need to update the knowledge base

Application Structure

In fact, Vuex has no restrictions on how to organize your code structure. Instead, it enforces a series of advanced principles:

1. The application-level state is concentrated in the store.

2. The only way to change the state is to submit mutations, which is a synchronous transaction.

3. Asynchronous logic should be encapsulated in action.

As long as you follow these rules, how to build the structure of your project is up to you. If your store file is very large, just split it into multiple files such as action, mutation and getter.

For slightly more complex applications, we may need to use modules. Here is a simple project architecture:

├──
├──
├── api
│   └── ... # Start an API request here
├── components
│   ├──
│   └── ...
└── store
├──
├──         # Root action
├──      # Root mutations
    └── modules
├── # cart module
└── # products module

About more, viewShopping cart example

Modules

Because of the use of a single state tree, all states of the application are contained within a large object. However, as our application scale continues to grow, this store has become very bloated.

To solve this problem, Vuex allows us to divide the store into modules. Each module contains its own state, mutation, action, getter, and even nested modules. The following is how it is organized:

const moduleA = {
 state: { ... },
 mutations: { ... },
 actions: { ... },
 getters: { ... }
}

const moduleB = {
 state: { ... },
 mutations: { ... },
 actions: { ... }
}

const store = new ({
 modules: {
 a: moduleA,
 b: moduleB
 }
})

 // -> moduleA's state
 // -> moduleB's state

Module local status

The first received parameter of the module's mutations and getters methods is the local state of the module.

const moduleA = {
 state: { count: 0 },
 mutations: {
 increment: (state) {
  // state is the module local state.  ++
 }
 },

 getters: {
 doubleCount (state) {
  return  * 2
 }
 }
}

Similarly, in the actions of the module, the local state is exposed, and the root state is exposed.

const moduleA = {
 // ...
 actions: {
 incrementIfOdd ({ state, commit }) {
  if ( % 2 === 1) {
  commit('increment')
  }
 }
 }
}

In the module's getters, the root state is also exposed as the third parameter.

const moduleA = {
 // ...
 getters: {
 sumWithRootCount (state, getters, rootState) {
  return  + 
 }
 }
}

Namespace

Note that actions, mutations, and getters within the module are still registered in the global namespace - this will cause multiple modules to respond to the same mutation/action type. You can add a prefix or suffix to the module's name to set the namespace to avoid naming conflicts. If your Vuex module is reusable and the execution environment is unknown, then you should do this. Distance, we want to create a todos module:

// 

// Define the constant names of getter, action, and mutation// and prefix `todos` to the module nameexport const DONE_COUNT = 'todos/DONE_COUNT'
export const FETCH_ALL = 'todos/FETCH_ALL'
export const TOGGLE_DONE = 'todos/TOGGLE_DONE'
// modules/
import * as types from '../types'

// Use prefixed names to define getters, actions and mutationsconst todosModule = {
 state: { todos: [] },

 getters: {
 [types.DONE_COUNT] (state) {
  // ...
 }
 },

 actions: {
 [types.FETCH_ALL] (context, payload) {
  // ...
 }
 },

 mutations: {
 [types.TOGGLE_DONE] (state, payload) {
  // ...
 }
 }
}

Register a dynamic module

You can register a module after store creation using the method:

('myModule', {
 // ...
})

Modular Exposed to the module's state.

Other Vue plug-ins can attach a module to the application's store, and then use Vuex's status management function through dynamic registration. For example, the vuex-router-sync library integrates vue-router and vuex by managing the application's routing state in a dynamically registered module.

You can use it too(moduleName) Remove dynamically registered modules. But you cannot use this method to remove static modules (that is, modules declared when the store is created).

Plugins

Vuex store receives the plugins option, which exposes the hooks of each mutation. A Vuex plugin is a simple method to receive sotre as the only parameter:

const myPlugin = store => {
 // Called when the store is initialized ((mutation, state) => {
 // Mutation is called afterwards // The format of mutation is {type, payload}. })
}

Then use it like this:

const store = new ({
 // ...
 plugins: [myPlugin]
})

Submit Mutations within the plugin

Plugins cannot modify state directly - this is like your components, they can only be changed by mutations.

By submitting mutations, the plug-in can be used to synchronize the data source to the store. For example, in order to synchronize websocket data sources to the store (this is just an example of usage, in practice, the createPlugin method will attach more options to complete complex tasks).

export default function createWebSocketPlugin (socket) {
 return store => {
 ('data', data => {
  ('receiveData', data)
 })
 (mutation => {
  if ( === 'UPDATE_DATA') {
  ('update', )
  }
 })
 }
}
const plugin = createWebSocketPlugin(socket)

const store = new ({
 state,
 mutations,
 plugins: [plugin]
})

Generate a status snapshot

Sometimes the plug-in wants to get state "snapshot" and changes before and after the state changes. To implement these functions, deep copy of the state object is required:

const myPluginWithSnapshot = store => {
 let prevState = _.cloneDeep()
 ((mutation, state) => {
 let nextState = _.cloneDeep(state)

 // Compare prevState and nextState...
 // Save the status, used for the next mutation prevState = nextState
 })
}

** The plug-in that generates state snapshots can only be used during the development stage. Use Webpack or Browserify to let the build tools help us handle:

const store = new ({
 // ...
 plugins: .NODE_ENV !== 'production'
 ? [myPluginWithSnapshot]
 : []
})

The plug-in will be activated by default. In order to publish a product, you need to use Webpack's DefinePlugin or Browserify's envify to convert the value of .NODE_ENV !== 'production' to false.

Built-in Logger plugin

If you are using vue-devtools, you probably don't need it.

Vuex brings a log plugin for general debugging:

import createLogger from 'vuex/dist/logger'

const store = new ({
 plugins: [createLogger()]
})

The createLogger method has several configuration items:

const logger = createLogger({
 collapsed: false, // Automatically expand the record mutation transformer (state) {
 // Convert before recording // For example, only the specified subtree is returned return 
 },
 mutationTransformer (mutation) {
 // mutation format { type, payload } // We can format it the way we want return 
 }
})

The log plugin can also be directly through the <script> tag, and it will then provide the global method createVuexLogger .

Note that the logger plugin generates state snapshots, so it is only used in development environments.

Strict mode

To enable strict mode, simply pass strict: true when creating the Vuex store.

const store = new ({
 // ...
 strict: true
})

In strict mode, an error will be thrown as long as the Vuex state is modified outside the mutation method. This ensures that all state modifications are explicitly tracked by the debugging tool.

Development stage vs. Release stage

Don't turn on strict mode during the release stage! Strict mode performs deep monitoring of the status tree to detect inappropriate modifications – making sure it is turned off during the release phase to avoid performance losses.
Similar to the situation of handling plugins, we can let the build tool handle:

const store = new ({
 // ...
 strict: .NODE_ENV !== 'production'
})


Related Quotations

/en/
/en/
/en/
/en/

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.