学习vuex(一):理解...mapActions,...mapMutations,...mapState

我们在项目中使用vuex,经常可以看到会写…mapState,…mapActions,…mapMutations

有的小伙伴会对…mapState等写法有疑惑。其实这是使用了ES6的扩展运算符,因为mapState,mapActions,mapMutations函数返回的都是一个对象,当我们需要在computed或者method中混用的时候,就需要…(扩展运算符)对函数进行展开。
例如…mapActions返回的是

{
	userInfo(){},
	addr(){}
}

那么通过扩展运算符把userInfo和addr拿出来放到method方法里面

如果mapState中所映射的计算属性名称与 state 的子节点名称相同时,我们可以给 mapState 传一个字符串数组:

computed:{
	...mapState([
			// 映射 this.a 为 store.state.a
			  'a',
			  'b',
			  'c'
	])
}

或者取个别名

...mapState({
	otherCount:  'count',  //把this.otherCount映射为this.$store.state.count
})

那么mapMutations和mapActions也是同样的操作,把mutation和action的方法绑定到method中:

...mapMutations([
	'a', //把this.a()映射为this.$store.commit('a')
	'b',
	'c'
])

...mapActions([
	'a', //把this.a()映射为this.$store.dispatch('a')
	'b'
])
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值