Skip to content

Latest commit

 

History

History
123 lines (98 loc) · 2.38 KB

index.md

File metadata and controls

123 lines (98 loc) · 2.38 KB
category
Utilities

reactivePick

Reactively pick fields from a reactive object.

Usage

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 }
// or
const pickedArr = reactivePick(obj, ['x', 'elementX']) // { x: number, elementX: number }
// or
const pickedArrRef = reactivePick(obj, ref(['x', 'elementX'])) // { x: number, elementX: number }

Scenarios

Selectively passing props to child

<script setup>
import { defineProps } from 'vue'
import { reactivePick } from '@vueuse/core'

const props = defineProps({
  value: {
    default: 'value',
  },
  color: {
    type: String,
  },
  font: {
    type: String,
  }
})

const childProps = reactivePick(props, 'color', 'font')
// or
const childPropsArr = reactivePick(props, Object.keys(ChildComp.props))
</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

import { reactive } from 'vue'
import { useElementBounding } from '@vueuse/core'

const { height, width } = useElementBounding() // object of refs
const size = reactive({ height, width })

Now we can just have this

import { reactivePick, useElementBounding } from '@vueuse/core'

const size = reactivePick(useElementBounding(), 'height', 'width')

Type Declarations

/**
 * Reactively pick fields from a reactive object
 *
 * Overload 1: pass keys individually
 *
 * @link https://vueuse.js.org/reactivePick
 * @param obj
 * @param keys
 */
export declare function reactivePick<T extends object, K extends keyof T>(
  obj: T,
  ...keys: K[]
): {
  [S in K]: UnwrapRef<T[S]>
}
/**
 * Reactively pick fields from a reactive object
 *
 * Overload 2: pass keys as (ref) array
 *
 * @link https://vueuse.js.org/reactivePick
 * @param obj
 * @param keys
 */
export declare function reactivePick<T extends object, K extends keyof T>(
  obj: T,
  keys: MaybeRef<K[]>
): {
  [S in K]: UnwrapRef<T[S]>
}

Source

SourceDocs