Vuex的使用方法第三篇之mapMutations,mapGetters、mapActions

本文介绍如何通过使用mapState、mapGetters和mapActions简化Vue.js应用程序中Vuex的状态管理和操作,减少代码冗余,提高开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多时候 , $store.state.count 、$store.dispatch('add') 这种写法又长又臭 , 很不方便 , 我们没使用 vuex 的时候 , 获取一个状态只需要 this.count , 执行一个方法只需要 this.add 就行了 , 使用 vuex 使写法变复杂了 ?

使用 mapState、mapGetters、mapActions 就不会这么复杂了。

以 mapState 为例 :

<template>
   <div>  
      <div>{{count}}</div>
      <input type="button" @click="$store.dispatch('addPlus')" value="+">
   </div>
</template>
<script>
import store from '../store/store'
import {mapState} from 'vuex';
export default {
  computed:
 //这里的三点叫做 : 扩展运算符
    ...mapState({
      count:state=>state.count
    })
//第二种方法
 //...mapState(['count'])
}
</script>

相当于 :

<template>
   <div>  
      <div>{{count}}</div>
      <input type="button" @click="$store.dispatch('addPlus')" value="+">
   </div>
</template>
<script>
import store from '../store/store'
import {mapState} from 'vuex';
export default {
   computed:{
    count(){
        return this.$store.state.count;
    }
  }
}
</script>

mapGetters、mapActions 和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值