to Computed
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)
)
}
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
})
}