Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/toRef.md
1---2category: Reactivity3alias: resolveRef4---56# toRef78Normalize value/ref/getter to `ref` or `computed`.910## Usage1112```ts13import { toRef } from '@vueuse/core'1415const foo = ref('hi')1617const a = toRef(0) // Ref<number>18const b = toRef(foo) // Ref<string>19const c = toRef(() => 'hi') // ComputedRef<string>20```2122## Differences from Vue's `toRef`2324VueUse's `toRef` is not the same as Vue’s `toRef` from the `vue` package.2526### VueUse `toRef`2728- Accepts **value**, **ref**, or **getter**29- Returns:30- a **ref** for primitive values31- a **ref** for existing refs32- a **computed** for getter functions33- Does **not** accept `object + key`34- Getters always produce readonly computed values3536### Vue `toRef`3738- Accepts only:39- a **reactive object + property key**, or40- an existing **ref**41- Produces a **writable ref** linked to the underlying reactive object42- Does **not** accept primitive values43- Does **not** accept getter functions4445### Summary4647| Behavior | VueUse `toRef` | Vue `toRef` |48| ------------------------ | ------------------------- | ----------------------- |49| Accepts primitive values | ✔️ | ❌ |50| Accepts getter | ✔️ (computed) | ❌ |51| Accepts existing ref | ✔️ | ✔️ |52| Accepts object + key | ❌ | ✔️ |53| Writable | ✔️ (except getter) | ✔️ |54| Purpose | Normalize to ref/computed | Bind to reactive object |5556## Type Declarations5758```ts59/**60* Normalize value/ref/getter to `ref` or `computed`.61*/62export declare function toRef<T>(r: () => T): Readonly<Ref<T>>63export declare function toRef<T>(r: ComputedRef<T>): ComputedRef<T>64export declare function toRef<T>(r: MaybeRefOrGetter<T>): Ref<T>65export declare function toRef<T>(r: T): Ref<T>66export declare function toRef<T extends object, K extends keyof T>(67object: T,68key: K,69): ToRef<T[K]>70export declare function toRef<T extends object, K extends keyof T>(71object: T,72key: K,73defaultValue: T[K],74): ToRef<Exclude<T[K], undefined>>75```76