API 文档 • 文档
函数: mapState()
允许在不使用组合式 API (setup()
) 的情况下使用一个 store 的 state 和 getters,通过生成一个对象来在组件的 computed
字段中展开。
参数
要映射的 store
参数
数组或对象
mapState(useStore, keyMapper)
mapState<
Id
,S
,G
,A
,KeyMapper
>(useStore
,keyMapper
):_MapStateObjectReturn
<Id
,S
,G
,A
,KeyMapper
>
允许在不使用组合式 API (setup()
) 的情况下使用一个 store 的 state 和 getters,通过生成一个对象来在组件的 computed
字段中展开。该对象的键值对是 state 属性/getters,而键是生成的计算属性的名称。可选地,你也可以传递一个自定义函数,该函数将接收 store 作为其第一个参数。请注意,虽然它可以通过 this
访问组件实例,但它不会被类型化。
类型参数
• Id extends string
• S extends StateTree
• G extends _GettersTree
<S
> | object
• A
• KeyMapper extends Record
<string
, keyof S
| keyof G
| (store
) => any
>
参数
• useStore: StoreDefinition
<Id
, S
, G
, A
>
要映射的 store
• keyMapper: KeyMapper
state 属性或 getters 的对象
返回值
_MapStateObjectReturn
<Id
, S
, G
, A
, KeyMapper
>
示例
export default {
computed: {
// other computed properties
// useCounterStore has a state property named `count` and a getter `double`
...mapState(useCounterStore, {
n: 'count',
triple: store => store.n * 3,
// note we can't use an arrow function if we want to use `this`
custom(store) {
return this.someComponentValue + store.n
},
doubleN: 'double'
})
},
created() {
this.n // 2
this.doubleN // 4
}
}
mapState(useStore, keys)
mapState<
Id
,S
,G
,A
,Keys
>(useStore
,keys
):_MapStateReturn
<S
,G
,Keys
>
允许在不使用组合式 API (setup()
) 的情况下使用一个 store 的 state 和 getters,通过生成一个对象来在组件的 computed
字段中展开。
类型参数
• Id extends string
• S extends StateTree
• G extends _GettersTree
<S
> | object
• A
• Keys extends string
| number
| symbol
参数
• useStore: StoreDefinition
<Id
, S
, G
, A
>
要映射的 store
• keys: readonly Keys
[]
state 属性或 getters 的数组
返回值
_MapStateReturn
<S
, G
, Keys
>
示例
export default {
computed: {
// other computed properties
...mapState(useCounterStore, ['count', 'double'])
},
created() {
this.count // 2
this.double // 4
}
}