mapState、mapMutations、mapAction的理解

作者 Lei Zhang 日期 2019-02-22
mapState、mapMutations、mapAction的理解

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。

官方文档中的说明:

mapState

  • mapState(namespace?: string, map: Array<string> | Object<string | function>): Object

    为组件创建计算属性以返回 Vuex store 中的状态。详细介绍

    第一个参数是可选的,可以是一个命名空间字符串。详细介绍

    对象形式的第二个参数的成员可以是一个函数。function(state: any)

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练,es6的箭头函数,传入参数是state,返回值是state.count。然后把返回值映射给count,此时调用this.count就是store里的count值
count: state => state.count,

// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',

// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}

mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。但是自从有了对象展开运算符(现处于 ECMASCript 提案 stage-4 阶段),我们可以极大地简化写法:

computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
mapMutations/mapActions只是把mutation/action函数绑定到methods里面,调里面的方法时正常传参数。