VUEX中关于 mapActions, mapMutations使用解析

在项目中,经常使用到VUEX状态管理,对于小项目中,直接使用

this.$store.commit('mutaion-name','参数')

或者

this.$store.dispatch('actions-name','参数')

上述两种方法即可。

但是,当项目中的 mutation 或者 action 过多的时候,这样一个个的写就显得比较麻烦。

所以,vue提供了 mapActions和mapMutations 。两者使用方法相似,下面以 mapActions为例。

一、引入 mapActions

import { mapActions } from 'vuex'复制代码

二、进行解构赋值和拓展运算

export default {
  // ...
  methods: {
       //下述中的 ... 是拓展运算符
       // 使用 [] 是解构赋值
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}复制代码

解析:

1. mapActions 必须放在 methods中,因为 action 或者 mutation 都是方法.

2. mapAction 里面事store 里面的集合,所以使用ES6中解构赋值的方法进行获取我们所需的方法。

3. mapAction 前面的 ( ... ) 是ES6中 拓展运算符,对我们所需的方法从数组中拓展出来。

4. ES6对象中同名属性可以简写。

5. 也可以自己命名不同函数名来映射 action方法


转载于:https://juejin.im/post/5cf9ba856fb9a07ef63fce62

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值