Skip to content
导航

mapActions

TIP

使用mapAction,获取store.actions

使用

ts
export default {
  created() {
    this.add()
  },
  methods: {
    ...mapActions(useCounterStore, {
      add: 'increment',
    })
  }
}

export default {
  created() {
    this.add()
  },
  methods: {
    ...mapActions(useCounterStore, [ 'add' ])
  }
}

源码

ts
export function mapActions<
  Id extends string,
  S extends StateTree,
  G extends _GettersTree<S>,
  A,
  KeyMapper extends Record<string, keyof A>
>(
  useStore: StoreDefinition<Id, S, G, A>,
  keysOrMapper: Array<keyof A> | KeyMapper
): _MapActionsReturn<A> | _MapActionsObjectReturn<A, KeyMapper> {
  return Array.isArray(keysOrMapper)
    ? keysOrMapper.reduce((reduced, key) => {
        reduced[key] = function (
          this: ComponentPublicInstance,
          ...args: any[]
        ) {
          return useStore(this.$pinia)[key](...args)
        }
        return reduced
      }, {} as _MapActionsReturn<A>)
    : Object.keys(keysOrMapper).reduce((reduced, key: keyof KeyMapper) => {
        reduced[key] = function (
          this: ComponentPublicInstance,
          ...args: any[]
        ) {
          return useStore(this.$pinia)[keysOrMapper[key]](...args)
        }
        return reduced
      }, {} as _MapActionsObjectReturn<A, KeyMapper>)
}

mapActions可以接受两个参数:useStore(一个useStore函数)、keysOrMapper(一个key列表,或map对象)。

mapActions返回一个对象。对象中的键通过keysOrMapper获得,如果keysOrMapper是个数组,那么key是数组中的元素,对应的值是函数,这个函数返回对应store[key]()的返回值。如果keysOrMapper是个对象,那么对象中键就是keysOrMapper中的键,对应的值是个函数,这个函数返回store[keysOrMapper[key]]()的返回值。

mapActions has loaded