Vue 3 Composition API patterns: feature-grouped setup code, composables with toValue inputs, ref vs reactive, computed, watch vs watchEffect, lifecycle and composable tests.
.cursor/rules/vue-3-composition-api-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Vue 3 Composition API patterns: feature-grouped setup code, composables with toValue inputs, ref vs reactive, computed, watch vs watchEffect, lifecycle and composable tests."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing Vue 3 components and composables with the Composition API.
## Organize by feature
- In `<script setup>`, keep the state, computed values, watchers and functions for one concern together instead of grouping by API type. When a concern grows or is reused, move it into a composable.
## Composables
- Name them `useX`, keep them in `composables/` (or next to the feature), and return an object of refs and functions so callers can destructure without losing reactivity.
- Accept reactive inputs as `MaybeRefOrGetter<T>` and read them with `toValue()` inside `watch`/`computed`, so callers can pass a value, a ref or a getter:
```ts
import { ref, toValue, watch, type MaybeRefOrGetter } from 'vue';
export function useFetchJson<T>(url: MaybeRefOrGetter<string>) {
const data = ref<T | null>(null);
const error = ref<Error | null>(null);
watch(
() => toValue(url),
async (current, _old, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort());
try {
const res = await fetch(current, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
data.value = (await res.json()) as T;
error.value = null;
} catch (e) {
if (!controller.signal.aborted) error.value = e as Error;
}
},
{ immediate: true }
);
return { data, error };
}
```
## ref vs reactive
- Prefer `ref` for state: it works for any value type and survives destructuring through `toRefs`. Use `reactive` for a grouped object you never reassign or destructure.
- Use `shallowRef` for large objects you replace as a whole (API responses).
## computed
- Use `computed` for values derived from state; keep it free of side effects. Use a writable computed only when a two-way derived value is needed (`get`/`set`).
## watch vs watchEffect
- `watch` when you need specific sources, the previous value, or lazy execution; `watchEffect` when the effect should track whatever it reads. Clean up timers, listeners and requests with `onCleanup` (or `onWatcherCleanup` in 3.5+).
- Do not use a watcher to keep one piece of state in sync with another; use `computed`.
## Lifecycle
- Register lifecycle hooks (`onMounted`, `onUnmounted`) synchronously in `setup` or in a composable called from it; hooks registered after an `await` are not attached to the component.
## TypeScript
- Use `<script setup lang="ts">` with type-based `defineProps<...>()` and `defineEmits<...>()`, and `defineModel()` (3.4+) for `v-model` props. Type refs that start empty (`ref<User | null>(null)`).
## Testing composables
- Test composables that use no lifecycle hooks or inject by calling them directly. For ones that do, mount a tiny host component (Vue Test Utils) or run them inside `effectScope()` and stop the scope after the test.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A search page has a long setup block grouped by API type (all refs, then all computeds, then all watchers) and duplicates fetch logic that ignores aborted requests.
Apply the Vue 3 Composition API Patterns rule to src/pages/SearchPage.vue and extract reusable logic.
Setup code regrouped by concern, a useFetchJson(url) composable that accepts a getter via MaybeRefOrGetter/toValue and aborts stale requests in onCleanup, computed instead of sync watchers, lifecycle hooks registered before any await, and a composable test plan using a host component or effectScope.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/vue-3-composition-api-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Vue 3 Composition API Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing Vue 3 components and composables with the Composition API.
## Organize by feature
- In `<script setup>`, keep the state, computed values, watchers and functions for one concern together instead of grouping by API type. When a concern grows or is reused, move it into a composable.
## Composables
- Name them `useX`, keep them in `composables/` (or next to the feature), and return an object of refs and functions so callers can destructure without losing reactivity.
- Accept reactive inputs as `MaybeRefOrGetter<T>` and read them with `toValue()` inside `watch`/`computed`, so callers can pass a value, a ref or a getter:
```ts
import { ref, toValue, watch, type MaybeRefOrGetter } from 'vue';
export function useFetchJson<T>(url: MaybeRefOrGetter<string>) {
const data = ref<T | null>(null);
const error = ref<Error | null>(null);
watch(
() => toValue(url),
async (current, _old, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort());
try {
const res = await fetch(current, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
data.value = (await res.json()) as T;
error.value = null;
} catch (e) {
if (!controller.signal.aborted) error.value = e as Error;
}
},
{ immediate: true }
);
return { data, error };
}
```
## ref vs reactive
- Prefer `ref` for state: it works for any value type and survives destructuring through `toRefs`. Use `reactive` for a grouped object you never reassign or destructure.
- Use `shallowRef` for large objects you replace as a whole (API responses).
## computed
- Use `computed` for values derived from state; keep it free of side effects. Use a writable computed only when a two-way derived value is needed (`get`/`set`).
## watch vs watchEffect
- `watch` when you need specific sources, the previous value, or lazy execution; `watchEffect` when the effect should track whatever it reads. Clean up timers, listeners and requests with `onCleanup` (or `onWatcherCleanup` in 3.5+).
- Do not use a watcher to keep one piece of state in sync with another; use `computed`.
## Lifecycle
- Register lifecycle hooks (`onMounted`, `onUnmounted`) synchronously in `setup` or in a composable called from it; hooks registered after an `await` are not attached to the component.
## TypeScript
- Use `<script setup lang="ts">` with type-based `defineProps<...>()` and `defineEmits<...>()`, and `defineModel()` (3.4+) for `v-model` props. Type refs that start empty (`ref<User | null>(null)`).
## Testing composables
- Test composables that use no lifecycle hooks or inject by calling them directly. For ones that do, mount a tiny host component (Vue Test Utils) or run them inside `effectScope()` and stop the scope after the test.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.