1.定义
01.vuex是vue的全局状态的管理工具
02.vuex数据更新,其引用组件都会响应式的更新
2.模块
state:存放数据的地方
组件中$store.state.xxx
state:{
cartNum:10
}
getters:从现有数据计算出新的数据
组件中$store.getters.xxx
getters:{
fee:function(state){return state.price*0.8}
}
mutations:改变state(唯一方式)
组件中$store.commit(方法,数据)
mutations:{
SET_CARTNUM(state,data){
state.cartNum = data;
}
}
actions:异步方法 组件中
$store.dispatch(方法,数据)
actions:{
setCart(context,data){
setTimeout(()=>{
context.commit("SET_CARTNUM",data)
},4000)
}
modules:
3.图解
4.模块的命名空间
作用:避免命名冲突
namespaced:true
state的访问默认是有命名空间的
getters,actions,mutations需要开启后才有命名空间
5.vuex映射
01.mapState把vuex的state 在computed映射为组件的data
...mapState({
score:state=>state.test.score
})
test是模块名,score数据名
02:mapGetters
没有命名空间
...mapGetters({
fee:"fee"
}),
...mapGetters(["fee"]),
有命名空间
...mapGetters({
"rank":"test/rank"
})
03.mapMutations
没有命名空间
...mapMutations({
"setUser":"SET_USERINFO"
})
有命名空间
...mapMutaions:{
"setScore":"test/SET_SCORE"
}
04.mapActions
没有命名空间
...mapActions({
login:"login"
}),
...mapActions(["login"])
}
有命名空间
...mapActions({
log:"test/login"
})