Create Adaptable Composable

作者 vuejs-aic9d355ff23f6MIT收錄於 2026年10月8日更新於 2026年10月8日

Create a library-grade Vue composable that accepts maybe-reactive inputs (MaybeRef / MaybeRefOrGetter) so callers can pass a plain value, ref, or getter. Normalize inputs with toValue()/toRef() inside reactive effects (watch/watchEffect) to keep behavior predictable and reactive. Use this skill when user asks for creating adaptable or reusable composables.

AI 產生的概覽

指導建立可接受一般值、ref 或 getter 輸入的可重用 Vue 組合式函式。

功能
此技能提供設計函式庫等級 Vue 組合式函式的說明,其參數可以是單純值、ref 或 getter。內容說明 MaybeRef 與 MaybeRefOrGetter 型別工具、各自適用時機,以及如何在反應式副作用中以 toValue() 或 toRef() 正規化輸入。文中也附上 useDocumentTitle 與 useCounter 等簡短範例。
適用情境
當使用者要求建立可調適或可重用的 Vue 組合式函式時使用。適合需要同時接受反應式與非反應式輸入的情境。鎖定 Vue 3 或 Nuxt 3 專案。
執行需求
需要 Vue 3(或以上版本)或 Nuxt 3(或以上版本)專案。不含指令碼,僅為說明文件。

Create Adaptable Composable

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.
  2. Identify inputs params that should be reactive (MaybeRef / MaybeRefOrGetter).
  3. Use toValue() or toRef() to normalize inputs inside reactive effects.
  4. Implement the core logic of the composable using Vue's reactivity APIs.

Core Type Concepts

Type Utilities

ts
/** * 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);

Policy and Rules

  • Read-only, computed-friendly input: use MaybeRefOrGetter
  • Needs to be writable / two-way input: use MaybeRef
  • Parameter might be a function value (callback/predicate/comparator): do not use MaybeRefOrGetter, or you may accidentally invoke it as a getter.
  • DOM/Element targets: if you want computed/derived targets, use MaybeRefOrGetter.

When MaybeRefOrGetter or MaybeRef is used:

  • resolve reactive value using toRef() (e.g. watcher source)
  • resolve non-reactive value using toValue()

Examples

Adaptable useDocumentTitle Composable: read-only title parameter

ts
import { 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

ts
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 }}

來源與署名

來源:vuejs-ai/skills位於skills/create-adaptable-composable提交c9d355f

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架