vuex的定义
vuex是vue的全局状态的管理工具
vuex数据更新,其引用组件都会响应式的更新
vuex的模块内容
state 存放数据的地方
组件中语法结构:
$store.state.xxx
state:{
cartNum:10
}
getters 从现有数据计算出新的数据
组件中语法结构:
$store.getters.xxx
getters:{
fee(state){ return state.price*0.5}
}
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 模块的命名空间
作用:避免命名冲突
注意: namespaced:true
state的访问默认是有命名空间的
getters,actions,mutations需要开启后才有命名空间
vuex的映射
mapState
把vuex的state 在computed映射为组件的data
test是模块名,score数据名
...mapState({
score:state=>state.test.score
})
mapGetters
没有命名空间
...mapGetters({
fee:"fee"
}),
...mapGetters(["fee"]),
有命名空间
...mapGetters({
"rank":"test/rank"
})
mapMutations
没有命名空间
...mapMutations({
"setUser":"SET_USERINFO"
})
有命名空间
...mapMutaions:{
"setScore":"test/SET_SCORE"
}
mapActions
没有命名空间
...mapActions({
login:"login"
}),
...mapActions(["login"])
}
有命名空间
...mapActions({
log:"test/login"
})