VueX相关知识点

一、组成部分

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",参数)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值