Vuex操作之辅助函数

851 阅读1分钟

这是我参与8月更文挑战的第6天,活动详情查看: 8月更文挑战” 。

上一篇介绍了Vuex入门的基本用法,在这里喔。在项目中的用法不仅仅是这些,特别是一些中大型的项目,状态比较多的情况下,这篇文章主要介绍一下Vuex中的辅助函数。

辅助函数有mapStatemapGettersmapActionsmapMutations,把vuex.store中的属性映射到vue实例身上,这样在vue实例中就能访问vuex.store中的属性了,对于操作vuex.store就变得非常方便。下面分别介绍每一个辅助函数的用法。

1. mapState 辅助函数

以前在没有使用辅助函数的时候通过this.$store.state.xx这种方式,如果当一个组件需要获取多个状态时候,将这些状态都声明为计算属性显然不合适,会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。代码更简洁。

  1. 首先需要引入mapState
import { mapState } from 'vuex'
  1. 在组件中使用,写在computed里面
computed: mapState({
    // 可以使用箭头函数
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

mapState 函数返回的是一个对象。可以使用...展开运算符,将他们和本组件其他计算属性混合在一起,这也是在项目中常用的一种方式。

computed: {
  ...mapState({
    // ...
  })
}

2. mapGetters 辅助函数

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。

  1. 首先需要引入mapGetters
import { mapGetters } from 'vuex'
  1. 在组件中使用,写在computed里面
export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'filterList',
      'listLen',
      // ...
    ])
  }
}

如果你想将一个 getter 属性另取一个名字,使用对象形式:

mapGetters({
  //`this.listLen` 映射为 `this.$store.getters.listNum`
  listLen: 'listNum'
})

3. mapMutations 辅助函数

mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用,换句话说就是把mutations中的方法映射到methods中,换一种调用方式。调用的时候就像调用本组件的method一样。

  1. 首先需要引入mapMutations
import { mapMutations } from 'vuex'
  1. 在组件中使用,写在methods里面
export default {
  // ...
  methods: {
    ...mapMutations([
       //`this.increment()` 映射为 `this.$store.commit('increment')`
      'increment', 

      // `mapMutations` 也支持载荷:
      // 将 `this.increamentPayload({ n: 10 })` 映射为 `this.$store.commit('increamentPayload', { n: 10 })`
      'increamentPayload' 
    ]),
    ...mapMutations({
      //`this.add()` 映射为 `this.$store.commit('increment')`
      add: 'increment' 
    })
  }
}

4. mapActions 辅助函数

mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用。换句话说就是把actions中的方法映射到methods中,换一种调用方式。调用的时候就像调用本组件的method一样。

  1. 首先需要引入mapActions
import { mapActions } from 'vuex'
  1. 在组件中使用,写在methods里面
export default {
  // ...
  methods: {
    ...mapActions([
       //`this.increment()` 映射为 `this.$store.dispatch('increment')`
      'increment', 

      // `mapActions` 也支持载荷:
      // 将 `this.increamentPayload({ n: 10 })` 映射为 `this.$store.dispatch('increamentPayload', { n: 10 })`
      'increamentPayload' 
    ]),
    ...mapActions({
      //`this.add()` 映射为 `this.$store.dispatch('increment')`
      add: 'increment' 
    })
  }
}