vuex是一个专为vue.js应用程序建立的状态管理模式,它采用集中式存储管理应用的所有组件的状态。
vuex中的几个重要的概念:store、state、mutation、action、getter
store:vuex将组件中的所有状态放到store中
state:组件状态,store的一次快照
mutation:vuex只允许提交一个mutation来改变state,mutation中只允许进行同步操作
action:调用commit触发mutation函数,可以进行异步操作
一个完整的store包括:state、mutation、action、getter
代码://创建store实例
const store = new Vuex.Store({
state:{
state1:'state1',
state2:'state2'
},
mutations:{
mutation1(state,payload){
state.state1 = payload.value;
},
mutation2(state,payload){
state.state2 = payload.value;
}
},
actions:{
action1(context,payload){
context.commit('mutation2',payload);
}
}
})
//在根组件中注入store,在各子组件中调用: this.$store.state.state1(使用state),this.$store.commit('mutation1',payload)--(提交一个mutation),this.$store.dispatch('action1',payload) --(dispatch一个action)
推荐在computed中设置获取state值供组件使用,使用mapState()辅助函数,将组件中的方法映射为commit mutation/dispatch action,使用mapMutations/mapActions
//组件中使用
export default{
computed:{
...mapState({
items:"items",
localItems(state){
return state.state1 + this.data1;
}
})
},
methods:{
...mapMutations({
'mutation1',
'mutation2'
})
...mapActions({
'action1',
'action2'
})
}
}