Skip to content

toRef

Category
Export Size
180 B
Last Changed
6 months ago

Normalize value/ref/getter to ref or computed.

Usage

ts
import { 
toRef
} from '@vueuse/core'
const
foo
=
ref
('hi')
const
a
=
toRef
(0) // Ref<number>
const
b
=
toRef
(
foo
) // Ref<string>
const
c
=
toRef
(() => 'hi') // ComputedRef<string>

Differences from Vue's toRef

VueUse's toRef is not the same as Vue’s toRef from the vue package.

VueUse toRef

  • Accepts value, ref, or getter
  • Returns:
    • a ref for primitive values
    • a ref for existing refs
    • a computed for getter functions
  • Does not accept object + key
  • Getters always produce readonly computed values

Vue toRef

  • Accepts only:
    • a reactive object + property key, or
    • an existing ref
  • Produces a writable ref linked to the underlying reactive object
  • Does not accept primitive values
  • Does not accept getter functions

Summary

BehaviorVueUse toRefVue toRef
Accepts primitive values✔️
Accepts getter✔️ (computed)
Accepts existing ref✔️✔️
Accepts object + key✔️
Writable✔️ (except getter)✔️
PurposeNormalize to ref/computedBind to reactive object

Type Declarations

ts
/**
 * Normalize value/ref/getter to `ref` or `computed`.
 */
export declare function 
toRef
<
T
>(
r
: () =>
T
):
Readonly
<
Ref
<
T
>>
export declare function
toRef
<
T
>(
r
:
ComputedRef
<
T
>):
ComputedRef
<
T
>
export declare function
toRef
<
T
>(
r
:
MaybeRefOrGetter
<
T
>):
Ref
<
T
>
export declare function
toRef
<
T
>(
r
:
T
):
Ref
<
T
>
export declare function
toRef
<
T
extends object,
K
extends keyof
T
>(
object
:
T
,
key
:
K
,
):
ToRef
<
T
[
K
]>
export declare function
toRef
<
T
extends object,
K
extends keyof
T
>(
object
:
T
,
key
:
K
,
defaultValue
:
T
[
K
],
):
ToRef
<
Exclude
<
T
[
K
], undefined>>

Source

SourceDocs

Contributors

Anthony Fu
ntnyq
Dayouzi
Vida Xie
IlyaL
Anthony Fu

Changelog

v14.0.0-alpha.2 on
971b2 - feat(shared)!: drop some deprecated apis (#5010)
v13.0.0 on
5e046 - feat!: drop CJS build, now it's ESM-only (#4581)
v12.8.0 on
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)

Released under the MIT License.

The new era of AI engineering.
Workflows, artifacts, and judgment that scale.
Request Early Access