vuex中的mapState 辅助函数

并不理解文档中辅助函数是怎么获取多个状态的??能不能详细简单的描述一下
mapState 辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

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

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

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

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

如果没有命名空间的话 他只是这样:

function mapState(map){
    const res = {}
    //对map进行Array或Object 进行判断部分省略
    map.forEach(({key, val})=>{
        res[key] = function mappedState () {
          let state = this.$store.state
          let getters = this.$store.getters
          
          return typeof val === 'function'
            ? val.call(this, state, getters)
            : state[val]
        }
    })
    return res
}

确实只是为了让你少敲几次代码而已

//正常
computed: {
    orderList(){
        return this.$store.state.orderList;
    },
    login(){
        return this.$store.state.login;
    }
}
//mapState
computed: {
    ...mapState([
        'orderList',
        'login'
    ]),
}

就是有多种写法的意思而已。写在computed里面,store改变的话对应的computed才会自动跟着改变

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题