Adaptable composables are reusable functions that can accept both reactive and non-reactive inputs. This allows developers to use the composable in a variety of contexts without worrying about the reactivity of the inputs. Steps to design an adaptable composable in Vue.js: 1. Confirm the composable's purpose and API design and expected inputs/outputs.
toValue() or toRef() to normalize inputs inside reactive effects./** * value or writable ref (value/ref/shallowRef/writable computed) */ export type MaybeRef<T = any> = T | Ref<T> | ShallowRef<T> | WritableComputedRef<T>; /** * MaybeRef<T> + ComputedRef<T> + () => T */ export type MaybeRefOrGetter<T = any> = MaybeRef<T> | ComputedRef<T> | (() => T);
MaybeRefOrGetterMaybeRefMaybeRefOrGetter, or you may accidentally invoke it as a getter.MaybeRefOrGetter.MaybeRefOrGetter or MaybeRef is used:toRef() (e.g. watcher source)toValue()useDocumentTitle Composable: read-only title parameterimport { watch, toRef } from 'vue' import type { MaybeRefOrGetter } from 'vue' export function useDocumentTitle(title: MaybeRefOrGetter<string>) { watch(toRef(title), (t) => { document.title = t }, { immediate: true }) } `Adaptable `useCounter` Composable: two-way writable count parameter` import { watch, toRef } from 'vue' import type { MaybeRef } from 'vue' function useCounter(count: MaybeRef<number>) { const countRef = toRef(count) function add() { countRef.value++ } return { add } }