Skip to content

⬅️ Back to Table of Contents

📄 toRefs

📊 Analysis Summary

Metric Count
🔧 Functions 1
📦 Imports 7
📐 Interfaces 1

📚 Table of Contents

🛠️ File Location:

📂 packages/shared/toRefs/index.ts

📦 Imports

Name Source
MaybeRef vue
MaybeRefOrGetter vue
ToRefs vue
_toRefs vue
customRef vue
isRef vue
toValue vue

Functions

toRefs(objectRef: MaybeRef<T>, options: ToRefsOptions): ToRefs<T>

Extended toRefs that also accepts refs of an object.

Parameters:

  • objectRef any: A ref or normal object or array.
  • options any: Options

See: https://vueuse.org/toRefs

Raw JSDoc
/**
 * Extended `toRefs` that also accepts refs of an object.
 *
 * @see https://vueuse.org/toRefs
 * @param objectRef A ref or normal object or array.
 * @param options Options
 */

Calls:

  • isRef (from vue)
  • _toRefs (from vue)
  • Array.isArray
  • Array.from
  • customRef (from vue)
  • toValue (from vue)
  • Object.setPrototypeOf
  • Object.getPrototypeOf
Code
export function toRefs<T extends object>(
  objectRef: MaybeRef<T>,
  options: ToRefsOptions = {},
): ToRefs<T> {
  if (!isRef(objectRef))
    return _toRefs(objectRef)

  const result: any = Array.isArray(objectRef.value)
    ? Array.from({ length: objectRef.value.length })
    : {}

  for (const key in objectRef.value) {
    result[key] = customRef<T[typeof key]>(() => ({
      get() {
        return objectRef.value[key]
      },
      set(v) {
        const replaceRef = toValue(options.replaceRef) ?? true

        if (replaceRef) {
          if (Array.isArray(objectRef.value)) {
            const copy: any = [...objectRef.value]
            copy[key] = v
            objectRef.value = copy
          }
          else {
            const newObject = { ...objectRef.value, [key]: v }

            Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value))

            objectRef.value = newObject
          }
        }
        else {
          objectRef.value[key] = v
        }
      },
    }))
  }
  return result
}

Interfaces

ToRefsOptions

Interface Code
export interface ToRefsOptions {
  /**
   * Replace the original ref with a copy on property update.
   *
   * @default true
   */
  replaceRef?: MaybeRefOrGetter<boolean>
}

Properties

Name Type Optional Description
replaceRef MaybeRefOrGetter<boolean> not shown

Generated by Syntax Scribe