vuex中辅助函数的使用方法

本文详细介绍了Vuex中的辅助函数使用,包括mapState用于映射state,mapGetters用于映射getters,mapMutations和mapActions则分别用于映射mutations和actions。这些函数简化了组件与Vuex状态管理的交互,通过computed和methods进行映射,并在组件中直接调用。当涉及多个modules时,可以通过命名空间路径或函数创建辅助函数。

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

1. mapState

import { mapState } from 'vuex'

export default {
  // ...
  computed:{
     ...mapState({
         // 箭头函数可使代码更简练
         count: state => state.count,
         // 传字符串参数 'count' 等同于 `state => state.count`
         countAlias: 'count',

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

定义的属性名与state中的名称相同时,可以传入一个数组

//定义state
const state={
    count:1,
}

//在组件中使用辅助函数
computed:{
    ...mapState(['count'])
}

2. mapGetters

computed:{
    ...mapGetters({
      // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
    })
}

当属性名与getters中定义的相同时,可以传入一个数组

总结:

  • mapState与mapGetters都用computed来进行映射
  • 在组件中映射完成后,通过this.映射属性名进行使用

3. mapMutations 

methods:{
    ...mapMutations({
        add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
}

 当属性名与mapMutatios中定义的相同时,可以传入一个数组

methods:{
    ...mapMutations([
        'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

        // `mapMutations` 也支持载荷:
        'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
}

 4. mapActios

mathods:{
    ...mapActions({
        add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
}

当属性名与mapActios中定义的相同时,可以传入一个数组

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

总结

  • mapMutations与mapActios都在methods中进行映射
  • 映射之后变成一个方法

 5. 多个modules

  • 在不使用辅助函数的时候,
this.$store.commit('app/addCount')
  • 使用辅助函数,辅助函数的第一个参数给定命名空间的路径
computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

或者使用 createNamespacedHelpers函数来创建一个基于命名空间的辅助函数

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') //给定路径
//使用方法与之前相同
export default {
  computed: {
    // 在 `some/nested/module` 中查找
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    // 在 `some/nested/module` 中查找
    ...mapActions([
      'foo',
      'bar'
    ])
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值