Skip to content
导航

mapState、mapGetters

TIP

使用mapState,获取store.statestate.getter

mapGettersmapState

使用

ts
export default {
  computed: {
    ...mapState(useCounterStore, {
      n: 'count',
      triple: store => store.n * 3,
      doubleN: 'double'
    })
  },
  created() {
    console.log(this.n)
    console.log(this.doubleN)
  },
}

export default {
  computed: {
    ...mapState(useCounterStore, [ 'count', 'double' ])
  },
  created() {
    console.log(this.count) 
    console.log(this.double) 
  },
}

源码分析

ts
export function mapState<
  Id extends string,
  S extends StateTree,
  G extends _GettersTree<S>,
  A
>(
  useStore: StoreDefinition<Id, S, G, A>,
  keysOrMapper: any
): _MapStateReturn<S, G> | _MapStateObjectReturn<Id, S, G, A> {
  return Array.isArray(keysOrMapper)
    ? keysOrMapper.reduce((reduced, key) => {
        reduced[key] = function (this: ComponentPublicInstance) {
          return useStore(this.$pinia)[key]
        } as () => any
        return reduced
      }, {} as _MapStateReturn<S, G>)
    : Object.keys(keysOrMapper).reduce((reduced, key: string) => {
        reduced[key] = function (this: ComponentPublicInstance) {
          const store = useStore(this.$pinia)
          const storeKey = keysOrMapper[key]
          return typeof storeKey === 'function'
            ? (storeKey as (store: Store<Id, S, G, A>) => any).call(this, store)
            : store[storeKey]
        }
        return reduced
      }, {} as _MapStateObjectReturn<Id, S, G, A>)
}

export const mapGetters = mapState

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

mapState会返回一个对象,这个对象的key值是通过keysOrMapper获得的。如果传入keysOrMapper是数组,返回对象的key就是keysOrMapper中的元素,key对应的值是个获取store[key]的函数。 如果keysOrMapper是个对象,返回对象的keykeysOrMapper中的keykey对应的值根据keysOrMapper[key]的类型有所区别,如果keysOrMapper[key]function,返回结果中对应key的值是一个返回keysOrMapper[key].call(this, store)的函数,否则key对应的是个返回store[keysOrMapper[key]]的函数。

mapGettersmapState

mapState、mapGetters has loaded