VueX声明状态为计算属性的写法,map函数

VueX中state中管理的数据(即状态),在组件中要访问时有4种写法;

定义一个简单的store.js文件,如下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{
            count:0,
            gender:'女',
            age:20
            },
    mutations:{},
    actions:{}

})

1、在组件中直接访问:

this.$store.state.数据名

//如访问gender
this.$store.state.gender

在组件的<template>中直接访问的时候,可以省略this:

<template>
    <div>

        <span>{{ $store.state.gender }}</span>

    </div>
</template>

2、但是像1中那么写,要写很多$store.state ,很麻烦。可以在计算属性中声明,以减少书写$store.state. 

在计算属性中声明有3种写法,第一种(computed中三种写法都是一样的):(我给count、gender都取了个新的名字——num、sex)

computed: {

  num:function abcdefg(){
    return this.$store.state.count
  },

  sex: function () {
    return this.$store.state.gender
  },

  age(){
    return this.$store.state.age
  }

则,之后在组件中访问state的数据时,可以直接写:

<template>
     <div>

        <span>{{ num }}</span>
        <span>{{ sex }}</span>
        <span>{{ age }}</span>

     </div>
</template>

3、但是第二种方法写的东西比第一种更多了...于是vuex给了一个函数mapState,来减少我们的工作量。

先在<script>中引入这个函数:

 import { mapState } from 'vuex'

 接着在computed中用,给mapState传入参数为一个对象,键表示我们定的别名,值为state中数据名,注意值要用引号括起来,否则将识别为该文件中函数。

computed: {

  ...mapState({

    num:'count',
    sex:'gender',
    age:'age'

  })

},

需要注意的是,调用mapState前加了三个点...

这个是js对象展开运算符。

为什么要加这三个点呢?

因为mapState函数返回值是一个对象,该对象里面包着三个函数(跟我们方法2写的函数一样的功能),大致就是:

{ num:f() , sex:f() , age:f()  }

computed本来就是一个对象了,里面再包一个对象要报错,所以用三点展开。比如:

let obj1 ={ a:1,b:2}

let obj2 = { c:3, ...obj1}

console.log(obj2)
//{c: 3, a: 1, b: 2}

4、最后一种写法是项目里常见的写法,当我不给state中的数据取新名字,而用他原来的名字,即:

computed: {

  ...mapState({

    count:'count',
    gender:'gender',
    age:'age'

  })

},

可以简写为:(注意,给mapState函数传入参数为一个数组!)

computed: {

  ...mapState(['count','gender','age'])

},

同理,mapGetters、mapActions、mapMutations的用法一致。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值