create-adaptable-composable

适应性可组合函数是可重用的函数,可以接受响应式和非响应式输入。这允许开发人员在各种上下文中使用可组合函数,而无需担心输入的响应性。

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "create-adaptable-composable" with this command: npx skills add hello-lizhihua/skills_zh-cn/hello-lizhihua-skills-zh-cn-create-adaptable-composable

创建适应性可组合函数

适应性可组合函数是可重用的函数,可以接受响应式和非响应式输入。这允许开发人员在各种上下文中使用可组合函数,而无需担心输入的响应性。

在 Vue.js 中设计适应性可组合函数的步骤:

  • 确认可组合函数的目的、API 设计以及预期的输入/输出。

  • 识别应该是响应式的输入参数 (MaybeRef / MaybeRefOrGetter)。

  • 在响应式副作用内使用 toValue() 或 toRef() 规范化输入。

  • 使用 Vue 的响应式 API 实现可组合函数的核心逻辑。

核心类型概念

类型工具

/**

  • 值或可写的 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);

策略和规则

  • 只读、计算属性友好的输入:使用 MaybeRefOrGetter

  • 需要是可写的 / 双向输入:使用 MaybeRef

  • 参数可能是函数值(回调/谓词/比较器):不要使用 MaybeRefOrGetter ,否则可能会意外地将其作为 getter 调用。

  • DOM/Element 目标:如果你想要计算/派生的目标,使用 MaybeRefOrGetter 。

当使用 MaybeRefOrGetter 或 MaybeRef 时:

  • 使用 toRef() 解析响应式值(例如侦听器源)

  • 使用 toValue() 解析非响应式值

示例

适应性 useDocumentTitle 可组合函数:只读标题参数

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

适应性 useCounter 可组合函数:双向可写计数参数

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

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

vue-best-practices

No summary provided by upstream source.

Repository SourceNeeds Review
General

vue-router-best-practices

No summary provided by upstream source.

Repository SourceNeeds Review
General

vue-pinia-best-practices

No summary provided by upstream source.

Repository SourceNeeds Review
General

vue-jsx-best-practices

No summary provided by upstream source.

Repository SourceNeeds Review