Vue 3 Engineering — Unified Architecture and Delivery Skill
Mission
Build Vue 3 applications that are understandable, type-safe, testable, accessible, and easy to change. Treat this document as an execution contract for an AI coding agent or a development team. Before editing code, inspect the existing project and preserve its conventions unless they conflict with an explicit requirement or a correctness issue.
The default stack is Vue 3 with <script setup>, the Composition API, TypeScript, Vite, Vue Router, Pinia when shared state is needed, Vitest for unit tests, Vue Test Utils for component tests, and Playwright for critical browser flows. A project may use alternatives, but every alternative must have a clear ownership and testing story.
Operating protocol
- Inspect
package.json,src/, route definitions, stores, test configuration, aliases, linting, and the build pipeline before proposing a structure. - State the project signals: expected size, team size, domain boundaries, deployment model, design-system needs, and whether independent delivery is required.
- Select the least complex architecture that satisfies those signals. Record the choice in an architecture note when the decision is not obvious.
- Define data and UI contracts before implementation: domain types, props, emits, slots, route params, store actions, loading/error states, and accessibility behavior.
- Implement the smallest vertical slice: route or entry point, view, components, composable/store, API boundary, and tests.
- Run type-checking, linting, unit/component tests, and the relevant end-to-end flow. Do not hide failures with casts, broad mocks, or disabled rules.
- Review the diff for dependency direction, duplicated state, unstable keys, missing cleanup, accidental public APIs, and regressions in keyboard and screen-reader behavior.
When requirements are incomplete, make the safest reversible assumption, isolate it behind a small interface, and leave a short TODO describing what must be confirmed. Do not invent API responses or domain rules merely to make a demo pass.
Non-negotiable engineering rules
- Prefer one-way data flow: parents pass props; children emit intentions; state owners perform mutations.
- Keep domain logic out of templates and keep reusable logic out of page components.
- Use stable identities for
v-forkeys. Never use the array index when an entity has an identity. - Keep effects explicit and cleaned up. Abort requests, remove listeners, and stop watchers when their scope ends.
- Make async state complete: idle/loading/success/empty/error, with retry behavior where useful.
- Do not expose a whole store or mutable object when a narrower API is enough.
- Do not use
anyto silence a design problem. Preferunknown, discriminated unions, generics, or a validated boundary. - Keep route names, emitted event names, store IDs, and public component props stable and intentional.
- Do not duplicate server state in multiple stores or components without a synchronization reason.
- Accessibility is part of the feature contract, not a final styling task.
1. Choose the project structure
Architecture is a constraint system, not a folder fashion. Choose according to change boundaries and dependency direction.
Flat structure: small projects
Use a flat structure for a prototype, proof of concept, pet project, or small MVP with one or two developers and few domains. Keep navigation obvious and avoid premature layers.
src/
assets/
components/
composables/
views/
router/
stores/
types/
App.vue
main.ts
Split a crowded directory by feature when files begin to be searched by naming convention, when a component requires feature-specific helpers, or when unrelated changes frequently touch the same files. Migrate incrementally; do not create a large architecture only to satisfy a diagram.
Modular structure: growing product
Use modules when a medium-sized product has recognizable business areas and several developers work in parallel.
src/
app/ # bootstrap, providers, router, global styles
modules/
billing/
api/
components/
composables/
routes.ts
stores/
types.ts
views/
catalog/
...
shared/
components/
composables/
lib/
styles/
types/
main.ts
A module owns its feature behavior. Shared code must be genuinely generic and must not import from a feature module. A feature may depend on shared code; sibling modules communicate through explicit contracts, not deep imports.
Feature-Sliced Design: large product with strict boundaries
Use FSD when the product has many domains, a growing team, or a strong need to prevent cross-feature coupling. Adapt the layers to the product rather than copying a directory tree mechanically.
src/
app/ # application wiring, providers, routing
pages/ # route-level composition
widgets/ # independent page sections
features/ # user actions and use cases
entities/ # business entities and their UI/data contracts
shared/ # domain-agnostic building blocks
Dependencies flow from higher-level composition toward lower-level building blocks. A slice should expose a public API from its index or designated entry point. Do not import another slice's internals.
Atomic Design: reusable visual system
Use atomic design when a product has a design system or a large number of repeated visual patterns. Keep atoms and molecules domain-neutral; keep organisms and templates compositional. Do not force business behavior into a button, input, or other primitive.
src/components/
atoms/
molecules/
organisms/
templates/
If a component needs domain data, permissions, routing, or mutation policy, it probably belongs at a feature, widget, or page level rather than in an atom.
FEOD or feature-oriented domain organization
Use feature-oriented domain organization when the team wants domain behavior grouped by business capability while still keeping a relatively direct project layout. Group screens, APIs, state, and tests by feature, then expose only intentional public contracts. This is often a pragmatic bridge between a flat MVP and a stricter layered architecture.
Micro-frontends
Use micro-frontends only when independent ownership, deployment, runtime isolation, or organizational boundaries are real requirements. They add versioning, navigation, shared dependency, loading, observability, and failure-mode costs. First establish module boundaries inside one application. A micro-frontend must have an explicit shell contract, independent build/deploy ownership, version policy, fallback UI, and end-to-end integration tests.
Architecture decision table
| Signal | Default choice | Avoid |
|---|---|---|
| Prototype or 1–2 developers | Flat | Empty abstraction layers |
| Several domains, one deployable app | Modular or feature-oriented | Global dumping grounds |
| Large product and many teams | FSD or a carefully adapted modular architecture | Cross-slice deep imports |
| Strong design system | Atomic components plus feature composition | Domain logic in atoms |
| Independent deploys and ownership | Micro-frontends | Splitting merely by route |
Dependency policy
Define aliases for stable public roots, not every directory. Enforce boundaries with lint rules, TypeScript path conventions, code review, or dependency-graph checks. A lower-level shared package must not import a page, feature, or application bootstrap. A route component may compose features; a low-level UI primitive must not know the router.
2. Design Vue components as contracts
A component is a boundary with a small public API. Design its inputs, outputs, slots, and state ownership before writing its template.
Props and emits
Use type-based declarations for TypeScript-first projects and runtime declarations when runtime metadata is important or the project is JavaScript-first. Defaults should be explicit. Keep props serializable and stable where possible.
<script setup lang="ts">
interface User {
id: string
name: string
avatarUrl?: string
}
const props = withDefaults(defineProps<{
user: User
compact?: boolean
disabled?: boolean
}>(), {
compact: false,
disabled: false,
})
const emit = defineEmits<{
select: [user: User]
remove: [userId: string]
}>()
</script>
<template>
<article :class="{ 'user-card--compact': props.compact }">
<button
type="button"
:disabled="props.disabled"
@click="emit('select', props.user)"
>
{{ props.user.name }}
</button>
<button
type="button"
:disabled="props.disabled"
@click="emit('remove', props.user.id)"
>Remove</button>
</article>
</template>
Name events as past-tense facts or clear user intentions and keep payloads narrow. Do not emit an entire mutable store when an ID or a domain command is sufficient. Prefer v-model only when the component represents an editable value and the update contract is clear.
Slots
Use slots for layout and controlled extension points. Name slots by purpose (header, actions, empty, loading) and document slot props. Do not use slots to conceal a large undocumented API. If the consumer needs many callbacks and internal details, the boundary probably belongs higher in the tree.
provide/inject
Use provide/inject for cross-cutting context that should flow through a subtree: form context, theme, table registration, or a service interface. Use a typed InjectionKey and fail clearly when a required provider is missing.
// formContext.ts
import type { InjectionKey, Ref } from 'vue'
export interface FormContext {
disabled: Ref<boolean>
registerField(name: string): void
}
export const formContextKey: InjectionKey<FormContext> = Symbol('form-context')
Do not use injection as a hidden global store. If state is application-wide, a store or an explicit service boundary is easier to inspect.
Component size and boundaries
A view owns route-level composition. A reusable component owns presentation and local interaction. A composable owns reusable reactive behavior. A store owns shared client state and domain actions. An API module owns transport and response mapping. Split when a component has multiple unrelated reasons to change, not merely because it has a certain number of lines.
3. Type the Composition API
Model domain types close to the domain boundary. Keep API DTOs separate from view models when their shape or nullability differs. Validate untrusted data at the boundary instead of asserting it is correct throughout the application.
interface ApiUserDto {
id: string
display_name: string
avatar_url: string | null
}
interface User {
id: string
name: string
avatarUrl?: string
}
function mapUser(dto: ApiUserDto): User {
return {
id: dto.id,
name: dto.display_name,
avatarUrl: dto.avatar_url ?? undefined,
}
}
Use ref<T>() for a value whose identity or type changes, reactive() for a cohesive object that should remain one reactive identity, and computed() for derived state. Do not destructure a reactive object if doing so loses reactivity; use toRefs or expose focused refs instead.
Type template refs according to the actual element or component instance and account for null before mount. Type event handlers from their real DOM or component event type instead of casting.
Prefer discriminated unions for state machines:
type LoadState<T> =
| { status: 'idle' }
| { status: 'loading'; requestId: number }
| { status: 'success'; data: T }
| { status: 'empty' }
| { status: 'error'; message: string; retryable: boolean }
Use unknown at untrusted boundaries, narrow it, and return useful errors. Keep generic utilities genuinely generic; do not add a generic parameter that is immediately cast away.
4. Composables and asynchronous work
A composable is a function named useX that groups reusable reactive behavior. It should have a clear input contract, explicit return contract, lifecycle-safe effects, and no surprising global mutation.
import { computed, onScopeDispose, ref, watch, type MaybeRefOrGetter, toValue } from 'vue'
export function useResource<T>(
source: MaybeRefOrGetter<string | null>,
load: (id: string, signal: AbortSignal) => Promise<T>,
) {
const data = ref<T>()
const error = ref<unknown>()
const loading = ref(false)
let controller: AbortController | undefined
let sequence = 0
const reload = async () => {
const id = toValue(source)
if (!id) return
controller?.abort()
controller = new AbortController()
const current = ++sequence
loading.value = true
error.value = undefined
try {
const next = await load(id, controller.signal)
if (current === sequence) data.value = next
} catch (cause) {
if (current === sequence && !(cause instanceof DOMException && cause.name === 'AbortError')) {
error.value = cause
}
} finally {
if (current === sequence) loading.value = false
}
}
watch(() => toValue(source), reload, { immediate: true })
onScopeDispose(() => controller?.abort())
return { data, error, loading, reload }
}
For async composables, define cancellation, stale-response handling, retries, cache policy, and error semantics. Do not let a late response overwrite newer state. Use effectScope in tests or reusable internal scopes when lifecycle ownership is otherwise ambiguous.
Compose small composables by responsibility: query parameters, pagination, keyboard navigation, and request state should not become one untestable mega-composable. Use VueUse when it provides a well-maintained primitive; wrap it when the application needs a domain-specific contract.
5. State management
Keep state at the lowest level that can own it correctly.
- Component-local state: temporary UI state, form drafts, open menus, hover or focus state.
- Composable state: reusable behavior with a clear lifecycle and limited sharing.
- Pinia store: shared client state, cross-route state, normalized entities, or domain actions used by multiple consumers.
- Server/cache layer: remote data, freshness, invalidation, pagination, and request deduplication.
- URL query/params: shareable, navigable state such as filters, tabs, and sort order.
Do not put every ref in Pinia. A store should expose state, derived getters, and domain actions; components should not reach through the store to mutate internal structures arbitrarily.
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCartStore = defineStore('cart', () => {
const lines = ref<Array<{ productId: string; quantity: number }>>([])
const totalItems = computed(() => lines.value.reduce((sum, line) => sum + line.quantity, 0))
function setQuantity(productId: string, quantity: number) {
if (quantity <= 0) {
lines.value = lines.value.filter(line => line.productId !== productId)
return
}
const line = lines.value.find(line => line.productId === productId)
if (line) line.quantity = quantity
else lines.value.push({ productId, quantity })
}
return { lines, totalItems, setQuantity }
})
Keep stores focused. Split by domain or use case rather than creating one global store. When state is persisted, define versioning, migration, sensitive-data rules, and reset behavior. Do not persist tokens or secrets in client storage without an explicit security decision.
6. Routing and navigation
Treat routes as a public application API. Use stable, semantic route names; keep names independent from component filenames and avoid ambiguous abbreviations. Define a route record with a clear name, path, lazy-loaded component, metadata, and an ownership boundary.
const routes = [
{
path: '/projects/:projectId',
name: 'project-detail',
component: () => import('@/modules/projects/views/ProjectDetailView.vue'),
meta: { requiresAuth: true, title: 'Project' },
},
]
Use params for resource identity and query parameters for filters, sorting, pagination, and other shareable view state. Validate and normalize route input before using it. Keep authorization in a guard or policy boundary, but enforce real authorization on the server as well.
Use navigation guards for cross-cutting navigation rules, not for arbitrary business mutations. Handle loading and failure when a lazy route or data dependency cannot load. Give not-found and unauthorized states intentional pages.
Implement back navigation with a predictable fallback. Browser history is not always meaningful when a user enters a deep link, opens a new tab, or comes from an external site. Preserve a safe return target only after validating it; never redirect to an untrusted arbitrary URL.
7. Styling and visual systems
Choose one primary styling strategy and document the exceptions. Component-scoped styles are useful for local rules; global styles are appropriate for resets, tokens, typography, and layout primitives. Use CSS variables for theme tokens and design decisions.
BEM is a practical naming convention when the project relies on authored CSS:
<template>
<article class="product-card" :class="{ 'product-card--featured': featured }">
<h2 class="product-card__title">{{ title }}</h2>
<div class="product-card__actions">...</div>
</article>
</template>
A block is a standalone component, an element belongs to that block, and a modifier changes state or variation. Do not encode arbitrary descendant selectors or mix unrelated blocks. Use data attributes for behavior hooks when class names are purely visual.
For a component library, choose the library based on accessibility, theming, bundle cost, SSR needs, customization, maintenance, and team familiarity. Quasar and Vuetify can provide broad application components; Reka UI can provide accessible unstyled primitives; a zero- or low-opinion library can be appropriate when the project already has a strong design system. Do not mix libraries casually: establish ownership for tokens, overlays, forms, focus management, and icons.
8. Testing strategy
Test behavior at the lowest level that gives confidence, then cover a small number of critical flows at the browser level.
Vitest unit tests
Use Vitest for pure functions, mappers, validators, composables, and store actions. Test observable contracts, edge cases, errors, cancellation, and state transitions. Avoid testing Vue internals or implementation details.
import { describe, expect, it } from 'vitest'
import { effectScope } from 'vue'
import { useCounter } from './useCounter'
it('increments within the composable scope', () => {
const scope = effectScope()
let counter!: ReturnType<typeof useCounter>
scope.run(() => { counter = useCounter(2) })
counter.increment()
expect(counter.count.value).toBe(3)
scope.stop()
})
Vue Test Utils component tests
Use mount when the integration of child components matters and shallowMount only when stubbing is intentional and does not hide the behavior under test. Verify props, rendered output, emitted events, slots, keyboard behavior, disabled/loading states, and integration with Pinia or the router through realistic test setup.
Do not assert private refs, exact generated class order, or framework internals. Prefer role, label, text, and public component contracts.
Playwright end-to-end tests
Reserve E2E tests for critical user journeys, route transitions, authentication boundaries, forms, payments or other high-risk flows, and integration points that unit tests cannot represent. Prefer accessible selectors (getByRole, getByLabel, getByTestId when needed) over CSS and brittle text fragments. Mock external APIs at the network boundary where determinism is required, while keeping at least a small set of environment-level integration checks.
import { test, expect } from '@playwright/test'
test('user can create a project', async ({ page }) => {
await page.goto('/projects')
await page.getByRole('button', { name: 'Create project' }).click()
await page.getByLabel('Project name').fill('Demo')
await page.getByRole('button', { name: 'Save project' }).click()
await expect(page.getByRole('heading', { name: 'Demo' })).toBeVisible()
})
Use a test pyramid: many fast unit tests, focused component tests, and fewer high-value E2E tests. Run the relevant tests near the change and the complete suite before merging. In CI, keep browser dependencies, retries, traces, and artifacts explicit.
9. Delivery quality: performance, accessibility, and security
Lazy-load route-level code and expensive feature code. Avoid unnecessary deep watchers, repeated derived calculations, and rendering huge lists without virtualization or pagination. Measure before optimizing; do not trade clarity for speculative micro-optimizations.
Every interactive control must be keyboard reachable and have an accessible name. Use semantic HTML first. Manage focus after dialogs, route changes, and validation errors. Do not use color alone to convey state. Make loading, empty, error, and disabled states perceivable. Test reduced motion where animation is essential.
Treat route params, query parameters, local storage, URL return targets, and API responses as untrusted input. Escape rendered content, avoid unsafe HTML, validate redirect targets, and do not place secrets in the client bundle. Client-side guards improve UX but never replace server authorization.
10. Recommended implementation workflow
Discovery
Read the repository and identify the existing architecture, public entry points, build commands, test commands, and neighboring examples. Search for the nearest analogous feature before creating a new pattern.
Contract design
Write the domain type, API mapping, component props/emits/slots, route record, store/composable interface, and expected states. Decide which state belongs in the URL, component, composable, store, or server cache.
Vertical slice
Implement the route or entry point, the primary view, the smallest reusable components, the data boundary, and one happy-path test. Add empty, loading, error, disabled, and permission states before polishing.
Hardening
Add cancellation and stale-response protection, keyboard behavior, validation, retry policy, responsive layout, error reporting, and tests for edge cases. Review dependencies and bundle impact.
Review and migration
Check naming, imports, public APIs, dependency direction, duplicated state, and removed code. If moving from flat to modular or from ad hoc components to a design system, migrate one feature at a time and preserve behavior with tests.
11. Common anti-patterns and corrections
| Anti-pattern | Correction |
|---|---|
| One global store contains every ref | Keep local state local and split stores by domain |
| Page component contains fetch, mapping, form, and all markup | Separate API mapping, composable/store logic, and reusable UI |
| Child mutates a prop or a parent-owned object silently | Emit a narrow event or use an explicit model contract |
any and non-null assertions everywhere | Type the boundary, narrow unknown, and model impossible states |
| Deep imports across feature internals | Expose a public entry point and enforce dependency direction |
| Array index used as a key | Use a stable domain ID |
| Watcher starts a request without aborting the previous one | Abort, sequence, and ignore stale responses |
| Every route guard performs business logic | Keep navigation policy separate from domain actions |
| Styling relies on unrelated global selectors | Scope local styles and use tokens/BEM or the chosen system |
| E2E tests query CSS implementation details | Use roles, labels, and stable test hooks |
| UI library components are mixed without ownership | Choose a primary library and define integration boundaries |
| Micro-frontends introduced for visual separation | Start with modules; split runtime ownership only when required |
12. Definition of done
- The chosen architecture is justified by project signals and does not add unused layers.
- Types describe the domain, API boundary, component contract, and async states.
- Props, emits, slots, route names, and store actions form a deliberate public API.
- Loading, empty, error, retry, disabled, and permission states are implemented.
- Requests are cancellable or otherwise protected against stale updates.
- Keyboard, focus, labels, semantics, and responsive behavior are covered.
- Unit or component tests cover the changed contract; a critical E2E path is added or updated when appropriate.
- Type-checking, linting, tests, and the production build pass.
- No secrets, unsafe redirects, accidental global state, deep internal imports, or dead dependencies were introduced.
- The diff is smaller and clearer than the problem requires; abstractions have a demonstrated consumer.
13. Compact decision guide
When choosing a folder structure, begin flat and move to modular, FSD, atomic, or micro-frontend boundaries only when team, domain, design-system, or deployment signals require them.
When choosing state, keep it local unless it must be reused, persisted, coordinated, or represented in the URL. Use Pinia for shared client domain state, not as a default dumping ground.
When choosing a reusable abstraction, start with a component for UI, a composable for reactive behavior, a store for shared client state, and a service/API module for transport or domain integration.
When choosing a test, use a unit test for deterministic logic, Vue Test Utils for a component contract, and Playwright for a critical user journey across real routing and browser behavior.
When choosing styling, use the existing system if it is coherent; otherwise establish tokens, a naming convention, ownership of global styles, and a single component-library strategy before adding more components.
Source coverage
This unified skill is intentionally organized as one execution document, while covering the source topics in the catalog: project structure, routing, styling, state management, TypeScript, composables, ready-made solutions, testing, component design, specifications, library selection, and skill authoring. The companion SOURCE-COVERAGE.md lists the exact English source documents included in the published catalog snapshot used to build this archive.