Skip to content
Skills Library
Programming · Building & coding

vue3-spa-patterns

/vue3-spa-patterns

Provides the Vue 3 SPA execution contract: Composition API authoring, Pinia-only state mutation, composable extraction, a single Axios instance with Response Pattern interceptors, mandatory data-test IDs, lazy routes, and reactivity performance rules. Use if the project uses Vue 3. Squad-internal execution contract loaded by agents via their Methodology Dependencies table.

Licence
MIT
Last repository change
21.10.2026

Assessment and security

90/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content25 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
4
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Provides the Vue 3 SPA execution contract: Composition API authoring, Pinia-only state mutation, composable extraction, a single Axios instance with Response Pattern interceptors, mandatory data-test IDs, lazy routes, and reactivity performance rules. Use if the project uses Vue 3. Squad-internal execution contract loaded by agents via their Methodology Dependencies table.

Original author description

Provides the Vue 3 SPA execution contract: Composition API authoring, Pinia-only state mutation, composable extraction, a single Axios instance with Response Pattern interceptors, mandatory data-test IDs, lazy routes, and reactivity performance rules. Use if the project uses Vue 3. Squad-internal execution contract loaded by agents via their Methodology Dependencies table.

How it works

  1. Quick card
  2. Worker Execution Contract
  3. Deep Dive
Original SKILL.md headings · 119 lines, 1,710 words
SKILL.md preview
---
name: vue3-spa-patterns
description: "Provides the Vue 3 SPA execution contract: Composition API authoring, Pinia-only state mutation, composable extraction, a single Axios instance with Response Pattern interceptors, mandatory data-test IDs, lazy routes, and reactivity performance rules. Use if the project uses Vue 3. Squad-internal execution contract loaded by agents via their Methodology Dependencies table."
---

# Vue 3 SPA Patterns

Frontend rigor equal to backend rigor. Components render; stores mutate; one Axios instance talks to the API; every interactive element is testable by ID.

## Quick card

Derived from the contract below for a ≤ 3-file change; no new rules (convention #8).

1. `<script setup lang="ts">`, typed `defineProps`/`defineEmits` (§ Authoring & Typing).
2. State mutates only in Pinia actions; no store `v-model` (§ State Boundary).
3. All HTTP through the shared Axios instance (§ HTTP Layer).
4. Every interactive element carries `data-test` (§ Testability).
5. Pair every listener, timer or subscription with teardown (§ Lifecycle & Reactivity Hygiene).

- Brief → the quick note (What / Where / How verified)
- Artifact → the capture at `{quick-root}/evidence/check.md`
- Handoff → the `## Result` bullet in `note.md`

## Worker Execution Contract

This is the operational spine. Follow it as written. For a change of ≤ 3 files outside a pipeline, the Quick card above is the contract; the full contract applies inside a lane.

### Authoring & Typing

- Composition API with `<script setup lang="ts">` is the default authoring style for every new component. Do not use the Options API in new code.
- Type all component boundaries: `defineProps<T>()` and `defineEmits<T>()` with explicit interfaces. No untyped or runtime-only prop declarations in new components.
- Typecheck with `vue-tsc --noEmit` (installed as a devDependency), never plain `tsc` — only `vue-tsc` validates both `<script>` and `<template>` blocks.

### Component Abstraction & Shared Packages

- **Multi-Frontend Shared Component Package Rule**: In multi-frontend projects, primitive UI controls (Buttons, Inputs, Dropdowns/Selects, Autocompletes, Date/Time Pickers) MUST live in a shared UI component package (e.g. `packages/ui`) — for 100% visual, behavioral, and accessibility consistency across frontends.
- **Component Abstraction & Custom UI Controls**: Raw native HTML inputs or unwrapped third-party UI controls are prohibited in application features — all primitives MUST be wrapped inside the shared component library.

### State Boundary (Architect's state-mutation boundary)

- Shared state is mutated ONLY inside Pinia store actions. Components never write to store state directly — no `store.someField = x`, no `$patch` from a component. Components read state (via getters/`storeToRefs`) and call actions.
- **Template `v-model` Store Prohibition**: Direct `v-model` binding in templates to Pinia store state properties (e.g., `v-model="store.someField"`) is strictly prohibited as it performs implicit state mutation outside store actions. Use explicit `:model-value` and `@update:model-value` event handlers, store actions, or local computed properties with getter/setter wrappers that call store actions.
- **Complex State Two-Way Binding Rule**: When using two-way data binding (like `v-model`) to complex reactive state (like arrays or objects), never bind directly to the root reference; bind to specific properties or use explicit event handlers to prevent overwriting the reference with a primitive value.
- Local, component-private state stays in `ref`/`reactive` inside the component. If two or more components need it, it belongs in a store.

### Reuse — Composables

- Extract shared logic into composables (`useXxx`) applying the Rule of Three: extract on the third occurrence, not speculatively on the first.
- A composable owns its own state and returns a narrow, typed surface. It never reaches into component internals.
- **Decide a composable's scope explicitly.** Per-caller state/effects live inside the composable body; app-wide singletons (one watcher on global/persisted state, one media-query listener, one storage sync) live at **module scope**, outside the exported function — the function returns handles only. A singleton registered inside the body multiplies silently per call site: no error, no failing test (rationale: [references/vue3-spa-patterns-rationale.md](references/vue3-spa-patterns-rationale.md)).

### HTTP Layer

- Exactly ONE shared Axios instance for the app. No ad-hoc `axios.create()` or raw `fetch` calls in components or stores.
- Generic response interceptor unwraps the backend's standardized Response Pattern so callers receive typed payloads, never envelope plumbing.
- Request interceptor centralizes auth headers. A 401 triggers the silent refresh-token flow with request queueing — concurrent failures wait on one refresh, then replay.

### Testability

- Every interactive DOM element (buttons, inputs, links, selects, toggles) carries a `data-test` ID. This is mandatory, not optional polish — but it is the **fallback** hook: specs select by role, label or text first and reach for `getByTestId` only where no accessible name exists, in the selector order `{PLUGIN_ROOT}/playwright-skill/SKILL.md` § Rules owns.
- Every routed view/page carries a stable `data-test` ID on its **root element**, naming the page (not its content) — without it, an E2E navigation assertion can't distinguish the target page from a 404 or fallback route (rationale: [references/vue3-spa-patterns-rationale.md](references/vue3-spa-patterns-rationale.md)).

### Routing & Performance

- **Routing Entry Eager Loading Rule**: Only the main root entry view (`/`) MAY be eagerly loaded; all other non-critical route components MUST be lazy-loaded using dynamic imports (`() => import(...)`).
- Prefer `computed` over `watch` for derived state; use `watch` only for genuine side effects.
- Use `shallowRef` for large structures where deep reactivity is not needed.
- Add `v-memo` only with profiling evidence showing a real render hotspot — never speculatively.

### Data Flow & Computation

Applies to every line you author or modify, greenfield or brownfield — code written under these rules never needs the Refactor Mode retrofit pass.

- **Query once per dataset per scope**: never repeat the same store/entity query (Pinia getter chains, Vuex-ORM `Entity.query()`/`.all()`/`.where()`) or the same transform in loops, computed, or watchers — take one snapshot and derive from it.
- **Indexes over scans**: a `.find()`/`.filter()` inside a loop is a design smell at authoring time — build a computed `Map` index (`byId: ComputedRef<Map<Id, Entity>>`, `grouped: ComputedRef<Map<Key, Entity[]>>`) and use `map.get(id)`. Indexes stay reactive to store changes; no manual caches without invalidation.
- **Single-pass iteration**: never filter/iterate the same array repeatedly (especially inside an outer loop — N×M scans). One `filter()` predicate with early returns, or one `for` loop that builds results. Precompute repeated values (lowercased query strings, `Set`s, parsed JSON) once.
- **Pure data helpers at the second occurrence**: extract `toIdMap`/`groupBy`/`indexBy` when the same transform appears twice — stateless helpers are cheaper than composables, so they extract earlier than the Rule of Three that governs composables.
- **Minimal reactivity**: wrap a value in `ref`/`computed` only when something reactive consumes it (template, watcher, reactive side-effect). Constants and pure derivations of non-reactive inputs are plain `const`.
- **One intentional presence check**: match the check to the type — `value != null` covers null+undefined; a bare truthy check only when `0`, `false`, and `""` are impossible or already invalid; never truthy-check an ID typed `string | number`. Don't stack redundant null/empty checks.

### Lifecycle & Reactivity Hygiene

- Every add/join/subscribe (DOM/global listeners, real-time hub groups like SignalR, manual `watch()` handles, store subscriptions) is paired with its remove/leave/unsubscribe on the same target with the same stable function reference — in `onUnmounted`, and ALSO in `onDeactivated` when keep-alive can hide the view. Never register with an anonymous inline handler that can't be removed; mount/activate paths must not register twice without prior cleanup.
- Every lodash `debounce`/`throttle` instance is `.cancel()`ed and every timer (`setTimeout`/`setInterval`/`requestAnimationFrame`) cleared on teardown; no deferred callback may touch services, DOM, or refs after unmount.
- Component-owned DOM is reached via template `ref` + subtree queries, never `document.getElementById`/`querySelector` (globals are legitimate only for click-outside, focus traps, teleported nodes).
- One side effect, one watcher: never write two watchers invoking the same side effect — share a single `run()` wrapper. Merge watchers only when side-effect, gating, AND options are identical; keep value-specific or `oldVal`-dependent watchers separate.

### Refactor Mode (legacy code only)

The rules above make new code retrofit-free. For **existing** code written before this contract, a refactor delegation follows the sequential zero-regression procedure in [references/vue3-refactor-playbook.md](references/vue3-refactor-playbook.md) — the phased walk that retrofits these same rules with documented Skipped items and a mandatory phase-checklist report.

### Verification Checklist

Before marking work complete:

- [ ] All new components use `<script setup>` with typed `defineProps`/`defineEmits`
- [ ] `vue-tsc --noEmit` has been **executed** and is clean — including unused imports/vars. `vite build` does not typecheck; a build that succeeds proves nothing about type validity.
- [ ] In multi-frontend projects, all primitive UI controls reside in a shared UI package (`packages/ui`)
- [ ] No component mutates shared state directly — all writes go through Pinia actions; no direct `v-model="store.someField"` bindings in templates
- [ ] All HTTP traffic flows through the single shared Axios instance and its interceptors
- [ ] The 401 path performs silent refresh + queued replay as specified — **no** page reload, forced logout, storage wipe, or hardcoded/stub token as a fallback.
- [ ] Every interactive element added or touched carries a `data-test` ID, and every routed view added or touched carries a page-naming `data-test` ID on its root element
- [ ] Only main entry route (`/`) is eagerly loaded; all other non-critical routes are lazy-loaded (`() => import(...)`)
- [ ] No watcher exists where a `computed` would do; no `v-memo` without profiling evidence
- [ ] Every listener/subscription/hub-join you added or touched has a matching teardown (`onUnmounted`, plus `onDeactivated` under keep-alive); every debounce/throttle/timer is cancelled on teardown
- [ ] No `document.getElementById`/`querySelector` for component-owned DOM — template refs used instead
- [ ] No repeated queries/scans: datasets queried once per scope, `Map` indexes instead of `.find()` in loops, no same-array multi-pass filtering
- [ ] No `ref`/`computed` wrapping a value nothing reactive consumes; no stacked redundant null/empty checks

### Escalate When

- The backend Response Pattern shape is undocumented or deviates from the standard envelope → report to the Orchestrator.
- A requirement forces direct state mutation outside a store action (e.g., third-party library writes) → report to the Orchestrator before violating the boundary.
- The refresh-token endpoint or auth contract is missing/ambiguous → report to the Orchestrator; do not invent an auth flow.

## Deep Dive

Read on demand — not needed to execute the contract above:

- [Vue 3 playbook](references/vue3-playbook.md) — GOOD/BAD code patterns: store action vs direct mutation, composable extraction, the full Axios interceptor setup with refresh-token queueing, `data-test` usage, lazy routes, and the computed-vs-watch anti-pattern.
- [Vue 3 refactor playbook](references/vue3-refactor-playbook.md) — the sequential zero-regression refactor pass: per-phase rules (loops, query indexes, watcher dedupe, reactivity removal, listener/timer cleanup, DOM refs, null checks), safety constraints, and the required Skipped/phase-checklist report format.
- [Vue 3 rationale](references/vue3-spa-patterns-rationale.md) — why composable singleton effects must live at module scope, and why the page-root `data-test` ID is a distinct requirement from interactive-element IDs.
Files in this package (4)
  • SKILL.md 12 KB
  • references/vue3-playbook.md 7 KB
  • references/vue3-refactor-playbook.md 7 KB
  • references/vue3-spa-patterns-rationale.md 2 KB

Versions

The database has no other skills named vue3-spa-patterns.

Database snapshot: 13.11.2026 · package version 1a9bad9caced (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100trove-vue
    Vue 3 Composition API conventions and best practices. Auto-activates when working with Vue single-file components. Covers reactivity, component patterns, Vue Router, and Pinia state management. Use when: vue component; composition api; pinia store.
  • 100vue-patterns
    Vue.js 3 Composition API patterns, component architecture, reactivity best practices, Pinia state management, Vue Router navigation, and Nuxt SSR patterns. Activates for Vue, Nuxt, Vite, or Pinia projects. Use when building or reviewing Vue 3, Nuxt, or Pinia code — Composition…
  • 100vue-patterns
    Vue.js 3 Composition API patterns, component architecture, reactivity best practices, Pinia state management, Vue Router navigation, and Nuxt SSR patterns. Activates for Vue, Nuxt, Vite, or Pinia projects. Use when building or reviewing Vue 3, Nuxt, or Pinia code — Composition…
  • 100vue
    Expert Vue 3 assistance covering Composition API (<script setup>), reactivity (ref, reactive), Pinia, and Vue Router. Use when developing modern, progressive web interfaces and single-page applications.
  • 100vue-patterns
    Vue.js 3 Composition API patterns, component architecture, reactivity best practices, Pinia state management, Vue Router navigation, and Nuxt SSR patterns. Activates for Vue, Nuxt, Vite, or Pinia projects. Use when building or reviewing Vue 3, Nuxt, or Pinia code — Composition…
  • 100pinia
    Pinia state management for Vue. Covers stores, actions, and getters. Use for Vue 3 state management. USE WHEN: user mentions "pinia", "vue state", "vue store", asks about "defineStore", "vue 3 state management", "composition stores", "vue global state", "storeToRefs", "pinia…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.