reactivePick
リアクティブオブジェクトからフィールドをリアクティブに選択します。
使用法
基本的な使用法
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 }
シナリオ
子コンポーネントへのpropsの選択的な受け渡し
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>
リアクティブオブジェクトの選択的なラップ
代わりにこれを行う
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')
型宣言
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]>
}
ソース
貢献者
変更履歴
v12.0.0-beta.1
2024/11/21v10.0.0-beta.4
2023/04/130a72b
- feat(toValue): resolveUnref
を toValue
にリネームv10.0.0-beta.2
2023/03/28