vuex mapState

使用vuex的mapState是为了获取state的映射关系的,在不使用mapState时候,采用computed中加入全局状态变量的方法如下


  computed: {
    count () {
      return this.$store.state.count
    }
  }

但是当组件中需要多个全局状态变量的时候,就很麻烦 使用mapState就可以快速建立映射关系:

方式1:数组

 

import { mapState } from 'vuex'
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: mapState([
  // 映射 this.count 为 store.state.count 数组的方式
      'count'
    ])
}

方式二:采用函数(但是注意如果想要使用data中的变量,必须是常规函数而不能是箭头函数)

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

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

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

方式三:扩展运算符(这种方式比较常用,不仅可以添加新的计算属性,而且可以随意映射state变量而且可以使用局部变量 this.localCount)

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
    count: state => state.count,
    countAlias: 'count',
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值