Demo address: github.com/bulang/vuex…

Vuex

concept

A set of state managers developed for vue.js programs

State

The data source of the project, the state of the entire project is stored in state.

 state:{
     number:123.name:'bulang'.sex:'boy'.infos: [{name:'kaisa'.sex:'boy'}, {name:'jiecaowa'.sex:'girl'}},Copy the code

Component to get state:

  • this.$store.state.key
  • Use auxiliary functionsmapState()Map the value of state to a component’s calculated property and expand it to use it directly in the component’s template:
    computed:{ ... mapState(['key']),}Copy the code

Mutation

Submission mutation is the only way to change state;

The first parameter is state, and the second parameter is user-defined payload.

Manipulate state synchronously, otherwise devTools records will have a history snapshot problem because asynchronous data cannot be tracked;

/ / case:
mutations: {add:(state, payload) = >{
        state.number+=payload.gap;
    },
    reduce:(state, payload) = >{ state.number-=payload.gap; }}Copy the code

Commit in componentmutationMethod:

  • this.$store.commit('add',{gap:5})

  • Use the auxiliary function mapMutations() to map the corresponding mutaions to the methods of the component and expand them, which can be directly used in the template of the component:

    / / case
    import { mapMutations } from 'vuex';
    export default {
        name:"active".methods: {
            ...mapMutations(['add'.'reduce'])}}Copy the code

Action

Main functions: Perform asynchronous operations (such as interface requests) and submitmutaion;

  • The first argument is a context object that has the same methods as the Store instance and can be destructed to get the methods on the object.

  • The second parameter is the value passed by custom;

  • Actions can be sent to each other;

/ / case:
actions: {toLog:({dispatch}, msg) = >{
        dispatch('promiseLog',msg).then(() = >{
            console.log('success');
        }).catch(() = >{
            console.log('error'); })},promiseLog:({commit},msg) = >{
        return new Promise((resolve, reject) = >{
            const i = ~~(Math.random()*10);
            console.log(i)
            if(i<5){
                commit('log',msg)
                resolve();
            }else{ reject(); }}); }},Copy the code

Distributed in the componentactionsMethod:

  • this.$store.dispatch('toLog','yes')

  • Use the helper function mapActions() to mapActions to the component’s methods and call them directly from the component’s template

    / / case:
    import {  mapActions } from 'vuex';
    export default {
        name:"active".methods: {
            ...mapActions(['toLog'])}}Copy the code

Getter

Main function: RightstateThe data is processed and used to derive new states

  • The first argument, state, provides the data;

  • The second argument can be passed to other getters, using other getters for the processed data;

  • We can return a function in the getter, so that when we use it, we can pass the parameter, according to the parameter to determine the data to return;

/ / case:
getters: {getInfo:state= >{
        return `my name is ${state.name}.${state.sex}`;
    },
    getCustomInfo:state= > index= > {
        return `my name is ${state.infos[index]['name']}.${state.infos[index]['sex']}`; }}Copy the code

Used in componentsgetters

  • this.$store.getters.getInfo

  • Use the helper function mapGetters to mapGetters to computed components and use them directly in component templates.

    / / case:
    import { mapGetters } from 'vuex'
    export default {
        name:'show'.computed: {... mapGetters(['getInfo'.'getCustomInfo'])}}Copy the code

Module

When the project is large enough, it can be difficult to maintain all the states, Mutaions, Actions, and getters in one file, so we need to pull the states, Mutaions, Actions, and getters out into their own files and export them.

  1. Each module has its ownstate.mutaions.actions.gettersFile;
  2. One for each moduleindex.jsFile unified export all methods;
  3. When exporting a module, you can specify whether to use a namespace, so that you can specify the corresponding module in the component to perform the corresponding operation.
  4. instoreImport all modules into the entry file;
  5. instantiationStoreAt the timemodulesInside pass module;
  6. When you use an auxiliary function, if you declare the use of the namespace, you can pass the specified module to the first argument of the auxiliary function.