コンテンツにスキップ

toRefs

カテゴリ
エクスポートサイズ
451 B
最終更新日
先週

オブジェクトのrefも受け入れる、拡張された toRefs です。

使用方法

ts
import { toRefs } from '@vueuse/core'
import { reactive, ref } from 'vue'

const objRef = ref({ a: 'a', b: 0 })
const arrRef = ref(['a', 0])

const { a, b } = toRefs(objRef)
const [a, b] = toRefs(arrRef)

const obj = reactive({ a: 'a', b: 0 })
const arr = reactive(['a', 0])

const { a, b } = toRefs(obj)
const [a, b] = toRefs(arr)

ユースケース

propsオブジェクトの分割代入

vue
<script lang="ts">
import { toRefs, useVModel } from '@vueuse/core'

export default {
  setup(props) {
    const refs = toRefs(useVModel(props, 'data'))

    console.log(refs.a.value) // props.data.a
    refs.a.value = 'a' // emit('update:data', { ...props.data, a: 'a' })

    return { ...refs }
  }
}
</script>

<template>
  <div>
    <input v-model="a" type="text">
    <input v-model="b" type="text">
  </div>
</template>

型宣言

typescript
export interface ToRefsOptions {
  /**
   * Replace the original ref with a copy on property update.
   *
   * @default true
   */
  replaceRef?: MaybeRefOrGetter<boolean>
}
/**
 * Extended `toRefs` that also accepts refs of an object.
 *
 * @see https://vueuse.dokyumento.jp/toRefs
 * @param objectRef A ref or normal object or array.
 */
export declare function toRefs<T extends object>(
  objectRef: MaybeRef<T>,
  options?: ToRefsOptions,
): ToRefs<T>

ソース

ソースドキュメント

コントリビューター

Anthony Fu
丶远方
Anthony Fu
Aaron-zon
Kasper Seweryn
ByMykel
vaakian X
chaii3
webfansplz
William T. Kirby

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除し、バンドルを最適化し、クリーンアップする (#4349)
v10.3.0 2023/7/30
5309c - fix: 不要な watchEffects をトリガーしないようにする (#3260)
v10.2.1 2023/6/28
9f998 - fix: 再帰的な setPrototypeOf によって引き起こされるスタックオーバーフローを修正する (#3166)

MITライセンスでリリースされています。