Skip to content

reactivePick

类别
导出体积
464 B
上次更改
6 minutes ago

从响应式对象中动态地选择字段。

用法

基本用法

ts
import { 
reactivePick
} from '@vueuse/core'
const
obj
=
reactive
({
x
: 0,
y
: 0,
elementX
: 0,
elementY
: 0,
}) const
picked
=
reactivePick
(
obj
, 'x', 'elementX') // { x: number, elementX: number }

条件用法

ts
import { 
reactivePick
} from '@vueuse/core'
const
source
=
reactive
({
foo
: 'foo',
bar
: 'bar',
baz
: 'baz',
qux
: true,
}) const
state
=
reactivePick
(
source
, (
value
,
key
) =>
key
!== 'bar' &&
value
!== true)
// { foo: string, baz: string }
source
.
qux
= false
// { foo: string, baz: string, qux: boolean }

场景

有选择地将属性传递给子组件

vue
<script setup lang="ts">
import { 
reactivePick
} from '@vueuse/core'
const
props
=
defineProps
<{
value
: string
color
?: string
font
?: string
}>() const
childProps
=
reactivePick
(
props
, 'color', 'font')
</script> <template> <
div
>
<!-- 只将 "color" 和 "font" 属性传递给子组件 --> <ChildComp v-bind="
childProps
" />
</
div
>
</template>

有选择地包装响应式对象

不再需要这样做

ts
import { 
useElementBounding
} from '@vueuse/core'
import {
reactive
} from 'vue'
const {
height
,
width
} =
useElementBounding
() // object of refs
const
size
=
reactive
({
height
,
width
})

现在我们可以简单地这样做

ts
import { 
reactivePick
,
useElementBounding
} from '@vueuse/core'
const
size
=
reactivePick
(
useElementBounding
(), 'height', 'width')

类型声明

ts
export type 
ReactivePickReturn
<
T
extends object,
K
extends keyof
T
> = {
[
S
in
K
]:
UnwrapRef
<
T
[
S
]>
} export type
ReactivePickPredicate
<
T
> = (
value
:
T
[keyof
T
],
key
: keyof
T
,
) => boolean export declare function
reactivePick
<
T
extends object,
K
extends keyof
T
>(
obj
:
T
,
...
keys
: (
K
|
K
[])[]
):
ReactivePickReturn
<
T
,
K
>
export declare function
reactivePick
<
T
extends object>(
obj
:
T
,
predicate
:
ReactivePickPredicate
<
T
>,
):
ReactivePickReturn
<
T
, keyof
T
>

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
丶远方
Arthur Darkstone
SerKo
Robin
Brain777777
Alex Kozack

更新日志

554b7 - fix: update return types for createTemplatePromise, useMagicKeys, use… (#4963)
c1d6e - feat(shared): ensure return types exists (#4659)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)