toComputed

A Vue 3 composable that slightly simplifies using a value that's a raw value, a ref, or a getter. Also supports providing a fallback for when the value is nullish.

typescriptjavascript
import { type MaybeRefOrGetter, type ComputedRef, computed, toValue } from 'vue'
 
export function toComputed<T>(
  source: MaybeRefOrGetter<T | null | undefined>,
  fallback: T | (() => T)
): ComputedRef<T>
export function toComputed<T>(source: MaybeRefOrGetter<T>): ComputedRef<T>
export function toComputed(source: MaybeRefOrGetter, fallback?: any) {
  return computed(
    () =>
      toValue(source) ??
      (typeof fallback === 'function' ? fallback() : fallback)
  )
}
import { computed, toValue } from 'vue'
 
export function toComputed(source, fallback) {
  return computed(
    () =>
      toValue(source) ??
      (typeof fallback === 'function' ? fallback() : fallback)
  )
}

Info

If you're using Nuxt (or just unimport directly), you can remove the imports at the top :).

Example

typescriptjavascript
import { type MaybeRefOrGetter } from 'vue'
 
export function useDoubledNumber(_number: MaybeRefOrGetter<number>) {
  const number = toComputed(_number)
 
  return computed(() => {
    return number.value * 2
  })
}
export function useDoubledNumber(_number) {
  const number = toComputed(_number)
 
  return computed(() => {
    return number.value * 2
  })
}
Created 20/02/24Updated 29/02/24
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here