Skip to content
On this page

toRefs

Category
Last Changed
3 months ago

Extended toRefs that also accepts refs of an object.

Usage

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

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)
import { toRefs } from '@vueuse/core'
import { reactive, ref } from 'vue-demi'

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)

Use-cases

Destructing a props object

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

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

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

Type Declarations

/**
 * Extended `toRefs` that also accepts refs of an object.
 *
 * @see https://vueuse.org/toRefs
 * @param objectRef A ref or normal object or array.
 */
export declare function toRefs<T extends object>(
  objectRef: MaybeRef<T>
): ToRefs<T>
/**
 * Extended `toRefs` that also accepts refs of an object.
 *
 * @see https://vueuse.org/toRefs
 * @param objectRef A ref or normal object or array.
 */
export declare function toRefs<T extends object>(
  objectRef: MaybeRef<T>
): ToRefs<T>

Source

SourceDocs

Contributors

Anthony Fu
William T. Kirby

Changelog

v6.8.0 on 11/6/2021
0219f - fix: call set method on computed (#895)
v4.9.0 on 4/21/2021
2fe00 - feat: new function (#468)
toRefs has loaded