我们在项目中使用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'
])