affaan-m/ECC

vue-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.

84CollectingNetwork access
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill "skills/vue-patterns"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn vue-patterns's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: Comprehensive guide for Vue.js 3 development using Composition API (), covering component design, reactivity, state management, routing, testing, and SSR patterns. Nuxt-specific guidance is included where it differs from vanilla Vue.

npx skills add https://github.com/affaan-m/ECC --skill "skills/vue-patterns"
Check the pinned source

Best fit

  • 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.

Bring this context

  • Use Setup Store syntax (not Options Store).
  • Prefer actions for business-level mutations and $patch() for grouped updates.
  • Every async action: handle loading + success + error.

Expected outputs

  • A result that follows the pinned vue-patterns instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read vue-patterns through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

Pinia Setup Store (Preferred)

Use Setup Store syntax (not Options Store).

SKILL.md · Pinia Setup Store (Preferred)
Use Setup Store syntax (not Options Store).Prefer actions for business-level mutations and $patch() for grouped updates.Every async action: handle loading + success + error.
02

When to Activate

Activate this skill when: - The project uses Vue.js (any version), Nuxt, Vite + Vue, or Pinia. - The user asks about Vue component architecture, composables, reactivity, or state management. - Reviewing Vue Single-File Components (.vue files). - Setting up Vue Router, Pinia stor…

SKILL.md · When to Activate
The project uses Vue.js (any version), Nuxt, Vite + Vue, or Pinia.The user asks about Vue component architecture, composables, reactivity, or state management.Reviewing Vue Single-File Components (.vue files).
03

1. Project Structure

Review the “1. Project Structure” section in the pinned source before continuing.

SKILL.md · 1. Project Structure
Review and apply the “1. Project Structure” source section.
04

Recommended Layout (Feature-First)

Review the “Recommended Layout (Feature-First)” section in the pinned source before continuing.

SKILL.md · Recommended Layout (Feature-First)
Review and apply the “Recommended Layout (Feature-First)” source section.
05

File Naming

Review the “File Naming” section in the pinned source before continuing.

SKILL.md · File Naming
Review and apply the “File Naming” source section.

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use vue-patterns to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned vue-patterns source to [task]. Pay particular attention to these source sections: “Pinia Setup Store (Preferred)”, “When to Activate”, “1. Project Structure”, “Recommended Layout (Feature-First)”, “File Naming”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current vue-patterns result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “Pinia Setup Store (Preferred)” has been checked.

The source section “When to Activate” has been checked.

The source section “1. Project Structure” has been checked.

The source section “Recommended Layout (Feature-First)” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does vue-patterns do?

Comprehensive guide for Vue.js 3 development using Composition API (), covering component design, reactivity, state management, routing, testing, and SSR patterns. Nuxt-specific guidance is included where it differs from vanilla Vue.

How do I start using vue-patterns?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill "skills/vue-patterns". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
84/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

84/100
Documentation30/30
Specificity19/25
Maintenance20/20
Trust signals15/25

Compare before choosing

Related Agent Skills and source variants

These links are selected from shared tasks, functions, stacks, platforms, and same-name variants. Compare the source owner, documentation, permissions, and maintenance signals.

View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 4 min

Vue.js Patterns and Best Practices

Comprehensive guide for Vue.js 3 development using Composition API (<script setup>), covering component design, reactivity, state management, routing, testing, and SSR patterns. Nuxt-specific guidance is included where it differs from vanilla Vue.

When to Activate

Activate this skill when:

  • The project uses Vue.js (any version), Nuxt, Vite + Vue, or Pinia.
  • The user asks about Vue component architecture, composables, reactivity, or state management.
  • Reviewing Vue Single-File Components (.vue files).
  • Setting up Vue Router, Pinia stores, or Vite/Vitest configuration.
  • Discussing Vue-specific performance, security, or SSR patterns.

1. Project Structure

Recommended Layout (Feature-First)

src/
├── api/              # API client and endpoint definitions
├── assets/           # Static assets (images, fonts, icons)
├── components/       # Shared/reusable components
│   ├── base/         # Base UI primitives (Button, Input, Modal)
│   └── features/     # Feature-specific shared components
├── composables/      # Reusable Composition API logic
├── layouts/          # Page layouts (optional)
├── pages/            # Route-level page components
├── router/           # Vue Router configuration
├── stores/           # Pinia stores
├── types/            # TypeScript type definitions
├── utils/            # Pure utility functions
└── App.vue           # Root component

File Naming

ConventionWhen to Use
PascalCase.vueAll components (enforced by vue/multi-word-component-names)
useCamelCase.tsComposables
camelCase.tsUtilities, API clients, types
kebab-case directoriesRoute segments, feature folders

2. Component Architecture

Single-File Component Order

<script setup lang="ts">
// 1. Imports (vue → ecosystem → absolute → relative)
// 2. Props & Emits & Slots
// 3. Composables
// 4. Local state (ref/reactive)
// 5. Computed properties
// 6. Methods
// 7. Watchers
// 8. Lifecycle hooks
</script>

<template>
  <!-- Template content -->
</template>

<style scoped>
  /* Scoped styles */
</style>

Presentational vs Container

  • Container components: Own data fetching, state, and side effects. Render presentational components.
  • Presentational components: Receive props, emit events. No API calls, no store access. Pure rendering.

Props Best Practices

// Type-based props with defaults
interface Props {
  label: string;
  variant?: "primary" | "secondary";
  disabled?: boolean;
  items: Item[];
}

const props = withDefaults(defineProps<Props>(), {
  variant: "primary",
  disabled: false,
});
  • Always provide type, and required/default where appropriate.
  • Boolean props: isXxx, hasXxx, canXxx.
  • Never mutate props — emit events instead.
  • For v-model binding, use defineModel() (Vue 3.4+) or modelValue + update:modelValue.

Events

const emit = defineEmits<{
  submit: [];
  "update:modelValue": [value: string];
  select: [id: string, index: number];
}>();
  • Use kebab-case in templates (@update:model-value).
  • Use camelCase in script (emit("update:modelValue", val)).

3. Composables (Reusable Logic)

Structure

// composables/useDebounce.ts
export function useDebounce<T>(value: MaybeRef<T>, delay: number): Ref<T> {
  const debounced = ref(toValue(value)) as Ref<T>;

  let timer: ReturnType<typeof setTimeout>;
  watch(
    () => toValue(value),
    (newVal) => {
      clearTimeout(timer);
      timer = setTimeout(() => { debounced.value = newVal; }, delay);
    }
  );

  onUnmounted(() => clearTimeout(timer));
  return readonly(debounced);
}

Rules

  • Must start with use prefix.
  • Return reactive values (ref, computed, reactive), never plain primitives.
  • Accept reactive inputs via MaybeRef / toRef() / toValue().
  • Clean up side effects in onUnmounted or watcher onCleanup.
  • No module-scope side effects.

vs Mixins

Composables replace Vue 2 mixins entirely:

  • Mixins: Opaque data flow, source-of-truth collisions, name conflicts.
  • Composables: Explicit imports, clear return values, composable and tree-shakable.

4. State Management

When to Use What

PatternUse Case
ref() / reactive()Local component state
Props + EmitsParent-child communication
Provide / InjectTheme, config, plugin API
Pinia storeGlobal, shared, complex state
Server state composableAPI data with caching (wrap fetch/TanStack Query)

Pinia Setup Store (Preferred)

// stores/useCartStore.ts
export const useCartStore = defineStore("cart", () => {
  const items = ref<CartItem[]>([]);
  const isLoading = ref(false);

  const totalPrice = computed(() =>
    items.value.reduce((sum, i) => sum + i.price * i.quantity, 0)
  );
  const itemCount = computed(() =>
    items.value.reduce((sum, i) => sum + i.quantity, 0)
  );

  async function addItem(productId: string) {
    isLoading.value = true;
    try {
      const item = await fetchProduct(productId);
      const existing = items.value.find(i => i.id === item.id);
      if (existing) existing.quantity++;
      else items.value.push({ ...item, quantity: 1 });
    } finally {
      isLoading.value = false;
    }
  }

  return { items, isLoading, totalPrice, itemCount, addItem };
});
  • Use Setup Store syntax (not Options Store).
  • Prefer actions for business-level mutations and $patch() for grouped updates.
  • Every async action: handle loading + success + error.

5. Vue Router

Route Definitions

const routes = [
  {
    path: "/users/:id",
    name: "user-detail",
    component: () => import("@/pages/UserDetail.vue"), // lazy
    props: true, // pass params as props
    meta: { requiresAuth: true },
  },
];

Navigation Guards

router.beforeEach((to, from) => {
  const { isLoggedIn } = useAuthStore();
  if (to.meta.requiresAuth && !isLoggedIn) {
    return { name: "login", query: { redirect: to.fullPath } };
  }
});

Reactive Route Params

When a component stays mounted but route params change:

const route = useRoute();
const id = computed(() => route.params.id as string);
watch(id, (newId) => fetchItem(newId));

6. Template Patterns

Template Syntax

<!-- v-if/v-else-if/v-else -->
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<div v-else>{{ content }}</div>

<!-- v-show for frequent toggles -->
<div v-show="isOpen">Toggled content</div>

<!-- v-for with stable keys -->
<div v-for="item in items" :key="item.id">{{ item.name }}</div>

<!-- Computed filtered list (not v-if + v-for on same element) -->
<div v-for="item in activeItems" :key="item.id">{{ item.name }}</div>

<!-- Event handling -->
<form @submit.prevent="handleSubmit">
  <button type="submit">Save</button>
</form>

<!-- v-model -->
<input v-model="name" />
<CustomInput v-model="value" v-model:title="title" />

7. Performance

TechniqueWhen to Use
v-memoList items that rarely change
v-onceContent rendered once and static forever
shallowRef()Large data structures replaced wholesale
shallowReactive()Only top-level properties are reactive
v-show over v-ifFrequent visibility toggles
<KeepAlive :max="10">Cache toggled views
Lazy routes() => import(...) for non-critical routes
SuspenseAsync component loading with fallback

8. Testing

Stack

  • Vitest for unit and component tests
  • Vue Test Utils for mounting and interaction
  • @pinia/testing for store mocking
  • Playwright for E2E

Component Test Pattern

import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import UserCard from "./UserCard.vue";

beforeEach(() => { setActivePinia(createPinia()); });

it("renders and emits", async () => {
  const wrapper = mount(UserCard, {
    props: { user: { id: "1", name: "Alice" } },
  });
  expect(wrapper.text()).toContain("Alice");
  await wrapper.find("button").trigger("click");
  expect(wrapper.emitted("select")![0]).toEqual(["1"]);
});

9. Nuxt-Specific Patterns

Auto-Imports

Nuxt auto-imports ref, computed, watch, useFetch, useAsyncData, etc. Use them directly without importing. For non-Nuxt projects, always import explicitly.

useAsyncData / useFetch

const { data: user, pending, error, refresh } = await useAsyncData(
  "user", // unique key for caching
  () => $fetch(`/api/users/${id}`),
);

const { data: posts } = await useFetch("/api/posts", {
  query: { page: 1 },
  key: "posts-page-1", // dedupes requests
});

Server Routes

// server/api/users/[id].ts
export default defineEventHandler(async (event) => {
  const { id } = await getValidatedRouterParams(event, z.object({
    id: z.string().uuid(),
  }).parse);
  // ... fetch and return
});

Runtime Config

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // server-only
    apiSecret: "",
    // public (exposed to client)
    public: {
      apiBase: "https://api.example.com",
    },
  },
});

10. Vue 3.5+ New APIs

Reactive Props Destructure

Vue 3.5 stabilized reactive props destructure — destructured variables from defineProps() are automatically reactive:

// Vue 3.5+: destructured props are reactive (no need for toRefs)
const { count = 0, msg = "hello" } = defineProps<{
  count?: number;
  msg?: string;
}>();

// Limitation: cannot watch destructured prop directly
watch(() => count, (newVal) => { ... }); // PASS getter required

useTemplateRef()

Replace name-matched plain refs with useTemplateRef() for template references:

import { useTemplateRef } from "vue";
const inputEl = useTemplateRef<HTMLInputElement>("input");
// "input" matches the ref="input" attribute in template, not the variable name

Supports dynamic ref IDs: useTemplateRef(dynamicRefId).

onWatcherCleanup()

Globally importable watcher cleanup API (Vue 3.5+). It must be called synchronously inside the watcher callback:

import { watch, onWatcherCleanup } from "vue";

watch(userId, async (newId) => {
  const controller = new AbortController();
  onWatcherCleanup(() => controller.abort());
  // ... fetch with signal
});

useId()

SSR-stable unique ID generation for form elements and accessibility:

import { useId } from "vue";
const id = useId();

defer Teleport

<Teleport defer> allows teleporting to targets rendered in the same cycle:

<Teleport defer to="#container">Content</Teleport>
<div id="container"></div>

Lazy Hydration (SSR)

defineAsyncComponent() now supports hydrate strategy:

import { defineAsyncComponent, hydrateOnVisible } from "vue";
const AsyncComp = defineAsyncComponent({
  loader: () => import("./Comp.vue"),
  hydrate: hydrateOnVisible(),
});

Anti-Patterns

Anti-PatternWhy It's WrongThe Fix
Destructuring defineProps() (Vue < 3.5)Captures snapshot, loses reactivityAccess via props.xxx or use toRefs()
watch() on destructured prop (Vue 3.5+)Compile-time error — destructured props can't be watched directlyUse getter wrapper: watch(() => count, ...)
v-if + v-for on same elementAmbiguous execution orderUse computed filtered array
v-for key = indexBroken state on reorderUse stable database IDs
Mutating propsViolates one-way data flowEmit events or use v-model
v-html with user contentXSS vulnerabilitySanitize with DOMPurify
Mixins in Vue 3Opaque, collision-proneReplace with composables
Module-scope side effects in composableShared across instancesScope in onMounted + onUnmounted
reactive() for replaceable stateReplacement breaks reactivityUse ref() instead
Watcher without cleanupMemory leaks, race conditionsUse onCleanup or onWatcherCleanup() (Vue 3.5+)
Options API in new Vue 3 codeEcosystem move to Composition APIUse <script setup>
Plain ref for template referencesNo dynamic ref support, name-matching fragileUse useTemplateRef() (Vue 3.5+)

Related Skills

  • accessibility — ARIA, semantic HTML, focus management
  • frontend-patterns — Cross-framework frontend architecture
  • typescript — TypeScript best practices applied to Vue projects
  • coding-standards — General code quality standards
Source repo
affaan-m/ECC
Skill path
skills/vue-patterns/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected