reactivePick
reactivePick
リアクティブなオブジェクトからフィールドをリアクティブに選択します。
使用法
基本的な使用法
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 }
条件付き使用法
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 }
シナリオ
子コンポーネントにプロップを選択的に渡す
<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>
リアクティブオブジェクトを選択的にラップする
次のようにする代わりに
import { useElementBounding } from '@vueuse/core'
import { reactive } from 'vue'
const { height, width } = useElementBounding() // refsのオブジェクト
const size = reactive({ height, width })
今では次のようにできます
import { reactivePick, useElementBounding } from '@vueuse/core'
const size = reactivePick(useElementBounding(), 'height', 'width')
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#