**vuex:弄懂mapState、mapGetters、mapMutations、mapActions**

vuex:弄懂mapState、mapGetters、mapMutations、mapActions

使用

<template>
  <div class="home">
    {{nickname}}
  </div>
</template>
<script>
export default {
  name: 'home',
  computed:{
    nickname(){
      return this.$store.state.nickname
    }
  }
}
</script>
mapState(['nickname','age','gender']) //映射哪些字段就填入哪些字段

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

展开符

...mapState(['nickname','age','gender'])
getters相当于vue中的计算属性
  getters:{
    realname(state){
      return state.firstname+state.lastname
    },
    money_us(state){
      return (state.money/7).toFixed(2)
    }
我们代码中定义的时候需要些mutations,它类似于vue中的methods
mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是state,第二个参数是载荷(payLoad),也就是额外的参数
mutations: { //类似于methods
  addAge(state,payLoad){
     state.age+=payLoad.number
  }
}

mapMutations
跟mapState、mapGetters一样

methods:{
 ...mapMutations(['addAge'])
}
mapMutations(['addAge'])这一句就相当于下面的代码

addAge(payLoad){
  this.$store.commit('addAge',payLoad)
}
参数我们可以在调用这个方法的时候写入

<button @click="addAge({number:5})">测试</button>
action类似于mutation

区别:action可以提交mutation

action也不要直接去操作state,而是去操作mutation

action包含异步操作,类似于axios请求,可以都放在action中写

action中的方法默认的就是异步,并且返回promise
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值