// root state object. // each Vuex instance is just a single state tree. const state = { count: 0 }
// mutations are operations that actually mutates the state. // each mutation handler gets the entire state tree as the // first argument, followed by additional payload arguments. // mutations must be synchronous and can be recorded by plugins // for debugging purposes.必须为同步方法 const mutations = { increment (state) { state.count++ }, decrement (state,amount) { state.count-= amount } }
// actions are functions that causes side effects and can involve // asynchronous operations. 可以加入异步方法 const actions = { // increment: ({ commit }) => commit('increment'), // decrement: ({ commit }) => commit('decrement'), incrementIfOdd ({ commit, state }) { if ((state.count + 1) % 2 === 0) { commit('increment') } }, incrementAsync ({ commit }) { returnnewPromise((resolve, reject) => { setTimeout(() => { commit('increment') resolve() }, 1000) }) } }
// A Vuex instance is created by combining the state, mutations, actions, // and getters. exportdefaultnew Vuex.Store({ state, getters, actions, mutations })