Vuex是一个专门为Vue.js应用程序开发的状态管理模式
1.state相当于组件中的data,专门用来存放全局数据
2.getters相当于组件中的computed,getters是全局的,computed是组件内部使用的
3.mutations相当于组件中的methods,但是它不能使用异步方法(定时器、axios)
更改Vuex的store中的状态的唯一方法是提交mutations
mutations:{
increase(state,payload){
state.num+=payload;
}
}
this.$store.commit('increase',2)
4.actions专门处理异步,实际修改状态值的依然是mutations
mutations:{
increase(state,payload){
state.num+=payload;
}
dec(state){
state.num--;
}
}
actions:{
decAsync(context){
context.commit('dec')
}
}
this.$store.dispatch('decAsync')
5.modules
我们的store可以认为是一个主模块,他下面可以分解为很多子模块,子模块都可以单独拎出来写,写完再导入到主模块中。下面以users子模块举例:
user模块也可以拥有state、getters、mutations和actions
所有的方法和属性, 该怎么写就怎么写。但users的index.js文件中,需要写入namespace:true 命名空间
然后在store的index.js中引入到modules中
在组件中获取值的方法:
$store.state.users.nickName
在组件中触发mutations的方法
methods:{
...mapMutations({
'changeNickname':'users/changeNickname'
})
}