跳到内容

reactivePick

类别
导出大小
477 B
上次更改
3 个月前

从响应式对象中响应式地挑选字段。

用法

基本用法

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]>
}

源码

源码文档

贡献者

Anthony Fu
Anthony Fu
丶远方
Brain777777
Alex Kozack

更新日志

v12.3.0 于 2025/1/2
59f75 - feat(toValue): 弃用 @vueuse/shared 中的 toValue,转而使用 Vue 原生方法
v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: 移除 Vue 2 支持,优化包并清理 (#4349)
v10.0.0-beta.4 于 2023/4/13
0a72b - feat(toValue): 将 resolveUnref 重命名为 toValue
v10.0.0-beta.2 于 2023/3/28
0bde4 - feat: 添加谓词参数 (#2850)

在 MIT 许可证下发布。