一、组成部分
1. state 状态
2. mutations 改变(修改state的唯一方式)
3. actions 动作(异步操作)
4. module 模块
5. getters 计算映射
二、在组件中访问vuex
1. 访问state
this.$store.state.xxx
2. 执行mutations方法
this.$store.commit("mutations名称",参数)
3. 执行actions方法
this.$store.dispatch("actions名称",参数)
4. 访问getters
this.$store.getters.xxx
三、便捷映射(mapState,mapMutations,mapActions,mapGetters)
1. state与getters通过computed映射
computed:{
...mapState(["user","num"]),
...mapGetters(["dnum"]),
...mapState({
cartNum:state=>state.cart.cartNum
}),
...mapGetters({
dcartNum:"cart/dcartNum"
})
}
2. mutations与actions通过methods映射
methods: {
// 把vuex的actions与mutations映射为本地方法
...mapMutations(["SET_NUM"]),
...mapActions(["login"]),
...mapMutations({
"setCartNum":"cart/SET_CARTNUM"
})
}
三、模块 module 把vuex分为多个子模块
1. 定义模块
// order.js
export default {
state:{total:88},
mutations:{
SET_TOTAL(state,payload){
state.total = payload;
}
},
getters:{
dtotal(state){
return state.total*2
}
}
}
2. 在 store/index.js 注册模块
import order from './order.js'
module:{order}
3. 组件中访问
默认只有state需要加命名空间,其他都不加
//访问state
this.$store.state.order.total
// 访问getters
this.$store.getters.dtotal
// 调用mutations、actions
this.$store.commit("SET_TOTAL",100)
四、模块的命名空间
1. 开启命名空间
namespaced:true
2. 访问要带命名空间
// state
this.$store.state.cart.cartNum
// getters
this.$store.getters["cart/dcartNum"]
// mutations
this.$store.commit("cart/SET_CARTNUM",参数)