Vuex-store: It is used to manage state between components, share data, and use properties in store together in projects

The installation

yarn add vuex

The introduction of vuex

impory Vuex from 'vuex'
Vue.use(Vuex)
Copy the code

Create a state store

let store = new Vuex.Store({
    state:{
        xxx:xxx
    }
})
Copy the code

Get data from this,$store.state. XXXX

Vuex operations

Vuex status management process

view -> actions -> mutations -> state -> view

Change state

Let store = new vuex. store ({state:{XXX: XXX}, mutations:{ add(state){ state.xxx = 111 } } })Copy the code

This. codestore.com MIT ('add') calls the add method inside mutations

Actions can include asynchronous actions, but mutations are submitted, rather than directly changing the state

let store = new Vuex.Store({
    state:{
        xxx:1
    },
    mutations:{
        add(state){
            state.xxx+=1
        },
        reduce(state){
            state.xxx-=1
        }
    },
    actions:{
        adds(context){
            setTimeout(()=>{
                context.commit(reduce)
            })
        }
    }
})
Copy the code

Getters is the judgment of state. Generally, getters is used to obtain the state of state

this.$store.getters.getXXX

let store = new Vuex.Store({
    state:{
        xxx:1
    },
    mutations:{
        add(state){
            state.xxx+=1
        },
        reduce(state){
            state.xxx-=1
        }
    },
    actions:{
        adds(context){
            setTimeout(()=>{
                context.commit(reduce)
            })
        }
    },
    getters:{
        getXxx(state){
            return state.xxx >0? state.xxx : 0
        }
    }
})
Copy the code