主题
reactivePick
从反应式性对象中反应式性地选取字段。
¥Reactively pick fields from a reactive object.
用法
¥Usage
基本用法
¥Basic Usage
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 }
谓词用法
¥Predicate Usage
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 }
应用场景
¥Scenarios
有选择地将属性传递给子级
¥Selectively passing props to child
vue
<script setup>
import { reactivePick } from '@vueuse/core'
const props = defineProps({
value: {
default: 'value',
},
color: {
type: String,
},
font: {
type: String,
}
})
const childProps = reactivePick(props, 'color', 'font')
</script>
<template>
<div>
<!-- only passes "color" and "font" props to child -->
<ChildComp v-bind="childProps" />
</div>
</template>
有选择地封装反应式对象
¥Selectively wrap reactive object
而不是这样做
¥Instead of doing this
ts
import { useElementBounding } from '@vueuse/core'
import { reactive } from 'vue'
const { height, width } = useElementBounding() // object of refs
const size = reactive({ height, width })
现在我们可以拥有这个
¥Now we can just have this
ts
import { reactivePick, useElementBounding } from '@vueuse/core'
const size = reactivePick(useElementBounding(), 'height', 'width')
类型声明
typescript
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[])[]
): {
[S in K]: UnwrapRef<T[S]>
}
export declare function reactivePick<T extends object>(
obj: T,
predicate: ReactivePickPredicate<T>,
): {
[S in keyof T]?: UnwrapRef<T[S]>
}