VUEX中关于 mapActions, mapMutations使用解析

9,626 阅读1分钟

在项目中,经常使用到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方法