Vuex popular version of the tutorial tells you how to use Vuex

Written before the text:

Recently been using vue development projects, write to write to is always such a method, for simple projects vue some commonly used method is sufficient to solve, but it comes to page status, privileges and some complex judgment passed by value, vuex is a must. For vuex also used for some time, but always felt something was lacking, or stay in the state will be used, and can not understand the essence, of course, the estimated level not reached. So always I wanted to find time to sum up vuex. To a deeper understanding, and secondly to facilitate future reference.

import Vue from 'vue'; 
import Vuex from 'vuex'; 
Vue.use(Vuex); 

const store = new Vuex.Store({ 
       state: { count: 0 },
       mutations: {
            increment (state) { 
                state.count++ 
            } 
      }
 })

The above is a simple Vuex, each store is a Vuex application, method component (temporarily called Method) mutations shared state status and state changes are included in the store.

The core vuex are: state, getter, actions, mutations

1、state

state is based on the needs of your project, you define a data structure, which may put some common state.

const state = {
  openId:"",
  storeId:"",
  storeName:''
}

For example written above, these states can be accessed by individual pages vuex. as follows:

this.$store.state.openId = "111"

Before I had been modified by the above way state inside the state value, OK, sure can, but it seems that this official is not to suggest that we use, but recommended mutations to change the value inside the state, because the state does not change through mutations, the state will not be synchronized. As mutations will be mentioned below.

2、getter

getter how to understand it? Popular understanding can be considered getter in the function is vuex in the calculation of property, similar to the computed function.

const store = new Vuex.Store({ 
       state: {
            count: 0 
       },
       getters: {  // getters
            countAdd: function (state) {
                 return state.count++
            }
       },
       mutations: {
            increment (state) { 
                state.count++ 
            } 
      }
 })

How to use getter function? As vuex in the definition of a getter function countAdd. We can calculate the computed attributes vue document's references, as follows.

computed: { 
     ... mapGetters {[ "countAdd" ]} 
     Show: function () { 
           Alert ( "This is a test page" ) 
     } 
}

We will be directly accessible to the pages vue countAdd value of {{countAdd}} is the 1. Unfortunately, my project was currently not used getter, probably written less, not understanding the essence of them.

3、mutations

The official definition: The only way to change Vuex the store in the state is to submit a mutation. Vuex of mutations is very similar to: Event Type (type) of each mutation has a string and a callback function (handler). The callback function is where we actually change the status, and it will accept the state as the first parameter:

Store = const new new Vuex.Store ({ 
  State: { 
    COUNT: . 1 
  }, 
  mutations: { 
    INCREMENT (State) { 
      // changed status 
      state.count ++ 
    } 
  } 
})

You can not directly call a mutation handler. This option is like event registration: "When a trigger increment type of mutation, this function is called." To wake up a mutation handler, you need to call store.commit method corresponding type:

store.commit('increment')

Can also pass a second parameter to store.commit, is the mutation of payload:

mutaion: {
    increment (state, n) {
        state.count += n;
    }
}
store.commit('increment', 10);

But sometimes, a single incoming n may not meet our business needs, this time we can choose to pass a payload objects:

mutation: { 
     increment (state, payload) { 
            state.totalPrice += payload.price + payload.count; 
     } 
} 
store.commit({
     type: 'increment', 
     price: 10, 
     count: 8
 })

Without exception, mutations are also mapping function mapMutations, help us simplify the code, use mapMutations auxiliary function assembly methods mapped to store.commit call.

{} from mapMutations Import 'vuex' 
Export default { 
  Methods: { 
    ... mapMutations ({ 
        the Add: 'INCREMENT' // . Mapping this.add () $ store.commit of the this ( 'INCREMENT') 
    }) 
  } 
} 
so we can directly call vue file function: the this .add () instead of $ store.commit the this ( 'INCREMENT'. ) wrote the following, simplified a lot. 
Note: Mutations must be synchronized function. 
If we need asynchronous operation, Mutations can not meet our needs, and this time we need the Actions.

4、action

Action similar mutation, except that:
Action submitting a mutation, rather than directly change state.
Action can contain any asynchronous operation.
The official demo as follows:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

If I want action, we can distribute vue pages in Action, Action triggered by store.dispatch method:

store.dispatch('increment')

Actions to support the same load mode and manner distribute objects:

// distributed in the form of a load 
store.dispatch ( 'incrementAsync' , { 
  AMOUNT: 10 
}) 

// distributed in the form of objects 
store.dispatch ({ 
  type: 'incrementAsync' , 
  AMOUNT: 10 
})

We can also use its mapping functions: mapActions

Methods: { 
     ... mapActions {[
            "the Add": "INCREMENT" // function names are not the same 
       //   "INCREMENT": "INCREMENT" // same function name 
     ]} 
} 
call: the this .add () can be. The same time calling: the this .increment ()

Modules

Due to the use of a single state tree, the status of all applications will be concentrated in a relatively large objects. When the application becomes very complicated, store the object is likely to become quite bloated.

To solve this problem, Vuex allow us to store is divided into modules (module). Each module has its own state, mutation, action, getter, even nested sub-module - split from top to bottom the same way:

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

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

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

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

To sum up: mutation just keep, you give me (dispatch) I keep; action just intermediate processing, processed and I'll give you, I do not care how you keep (all changes state to state are mutation operation); Getter I just take, I do not change (similar to the calculation of property).

About vuex currently understand it so much, what vuex in the actual project, how to use, but also need to be flexible to change, after slowly explore it. The example above many of which are vuex on the document, summed up still need to look at the document, use the actual project, it is the best way.

Guess you like

Origin www.cnblogs.com/wpcnblog/p/10973356.html