是什么
采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
组成
- state:每个应用包含一个 store 实例
- 在vue组件中,可通过计算属性从store中读取某个状态。
- getter:类似store的计算属性。
- mutation:更改state的方法
- 是同步函数
- action:类似mutation,是异步的,在action内commit mutation
- module:store可以被分割成module来避免臃肿.
- module的getter和mutation接受局部state作为参数
结构示意图
代码示例
const CERTARN_MUTATION = 'CERTARN_MUTATION'
const subModule = { state:{...}, ... }
const store = new Vuex.Store({
state:{
exampleState:'123'
},
getters:{
exampleGetter:state => { // 通过属性访问
return state.exampleState.concat('456')
},
exampleGetter2:(state)=>(str2)=>{ // 通过方法访问
return state.exampleState.concat(str2)
}
},
mutations:{
exampleMutation (state,payload) { // 传入该mutation的payload
state.exampleState = payload.str
},
[CERTARN_MUTATION] (state,payload) { // 建议用常量的方式构建mutation
state.exampleState = payload.str
}
},
actions:{
exampleAction ({ commit }) {
setTimeout(() => {
commit('exampleMutation',payload)
},1000)
},
async actionA ({ commit }) { // 可以用async和await来组合action
commit('gotData', await getData())
}
},
modules:{
sub:subModule
}
})
store.getters.exampleGetter
store.getters.exampleGetter2('456')
store.commit('exampleMutation',{ // 通过commit触发mutation,建议用对象的方式传入payload
str:'456'
})
store.commit({ // 对象风格的commit方式
type:'exampleMutation',
str:'456'
})
store.dispatch('exampleAction',payload)
store.state.sub