Vex2.0 state management

In vue. js, two ways are provided to facilitate communication management for different application projects: 1. Small single-page projects adopt communication between components; 2. Second, the development of large single-page applications usually adopt vEX2.0 state mechanism to achieve communication.

What is Vuex?

Vex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of the application, and the corresponding rules ensure that the state changes in a predictable one-way data flow.

Vex2.0 has several major changes

2. Obtain Vuex state, computed and mapState in the Vue component

Since Vuex’s state store is reactive, the easiest way to read state from a Store instance is to return some state in a calculated property:

  • Computed properties

Attributes are computed to solve the data operation of expressions in templates, and can be computed to cache decoupled code.

In Vuex, states in store instances can be read through computed computations. When store.state.count changes, the calculated attributes will be recomputed and the associated DOM will be updated.

// Create a Counter component // Global state singleton, const Counter = {template: '<div>{{count}}</div>', computed: {return store.state.count}}} // local state singleton, recommended, store register to the root instance const Counter = {template: `<div>{{ count }}</div>`, computed: { count () { return this.$store.state.count } } }Copy the code

Every time store.state.count changes, the calculated property is refetched and an update to the associated DOM is triggered.

  • MapState helper function

When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties that will save you from pressing the key:

MapState import {mapState} from 'Vuex' export default {//... Computed: mapState({// Arrow function makes code more concise count: This.$store.state => state.count, // Pass string 'count' equal to 'state => state.count' countAlias: 'count', // To be able to get local state with 'this ', CountPlusLocalState (state) {return this.$store.state.count + this.localCount}})}Copy the code

4. Combine Actions asynchronously

Actions are usually asynchronous. Store. dispatch can handle the Promise returned by the triggered Action’s callback function, and store.dispatch still returns a Promise knowing when the Action will end. It is easy to combine multiple actions to handle more complex asynchronous processes.

Active Previous asynchronous promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
Copy the code

Now a better way is to:

// Store the form actions: {//... actionB ({ dispatch, Commit}) {return dispatch('actionA'). Then (() => {commit('someOtherMutation')})}} // form inside component store.dispatch('actionA').then(() => { // ... })Copy the code

With the upcoming async/await feature of JavaScript, we can combine actions like this

// Suppose getData() and getOtherData() return Promise actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, Commit}) {await dispatch('actionA') // await actionA to complete commit('gotOtherData', await getOtherData())}}Copy the code

Local state of a module

For mutation and getters inside a module, the first argument received is the module’s local state object.

const moduleA = { state: { count: 0 }, mutations: {increment (state) {// where the 'state' object is the local state of the module state.count++}}, getters: { doubleCount (state) { return state.count * 2 } } }Copy the code

Similarly, for actions within the module, the local state is exposed through context.state and the rootState is context.rootState:

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}
Copy the code

For getters inside the module, the root node state is exposed as a third parameter:

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

Copy the code

6. Dynamic module registration

After the store is created, you can register the module using the store.registerModule method:

// registerModule 'myModule' store.registerModule('myModule', {//... }) // Register nested modules 'nested /myModule 'store.registerModule(['nested', 'myModule'], {//... })Copy the code

Can be used after store. State. MyModule and store state. Nested. MyModule access module.

References:

Vex2.0 official document

Vuex2.0 design