vuex
vuex定义
vuex是vue的全局状态的管理工具
vuex数据更新,其引用组件都会响应式的更新
vuex模块
1.state
存放数据的地方
组件中
$store.state.xxxstate:{ cartNum:10 }
2.getters
从现有数据计算出新的数据
组件中
$store.getters.xxxgetters:{ fee(state){ return state.price*0.5} }
3. mutations
改变state(唯一方式)
组件中
$store.commit(方法,数据)mutations:{ SET_CARTNUM(state,data){ state.cartNum = data; } }
4. actions
异步方法
组件中
$store.dispatch(方法,数据)actions:{ setCart(context,data){ setTimeout(()=>{ context.commit("SET_CARTNUM",data) },4000) } }
5. modules
模块的命名空间
作用:避免命名冲突
namespaced:true
state的访问默认是有命名空间的
getters,actions,mutations需要开启后才有命名空间
vuex的映射
mapState
把vuex的state 在computed
映射为组件的data...mapState({ score:state=>state.test.score }) 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"
})