---
name: vue-composition
description: "Vue 3 Composition API: ref, reactive, computed, watch, composables, Pinia state management, Vue Router 4, script setup. Use when building or reviewing Vue 3 work with the Composition API, composables or Pinia."
metadata:
  source: multi-agent-pipeline
  tags: [vue, composition-api, pinia, vue-router, frontend, javascript]
  version: "2025.1"
---

# Vue 3 Composition API

## Core Concepts

Vue 3 Composition API with `<script setup>` is the standard for new Vue projects. It provides
better TypeScript support, composable logic reuse, and cleaner code organization compared to
the Options API.

## Script Setup Syntax

```vue
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import type { User } from '@/types';

// Props with defaults
interface Props {
  title: string;
  count?: number;
  user: User;
}
const props = withDefaults(defineProps<Props>(), {
  count: 0,
});

// Emits with typed payload
const emit = defineEmits<{
  update: [value: string];
  delete: [id: string];
  submit: [];
}>();

// Expose public methods to parent via template ref
defineExpose({
  reset: () => { /* ... */ },
});

// Model (v-model two-way binding)
const modelValue = defineModel<string>({ required: true });

// Reactive state
const isLoading = ref(false);
const searchQuery = ref('');
const items = ref<User[]>([]);

// Computed
const filteredItems = computed(() =>
  items.value.filter((item) =>
    item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
);

// Methods
async function fetchItems() {
  isLoading.value = true;
  try {
    items.value = await api.getUsers();
  } finally {
    isLoading.value = false;
  }
}

// Lifecycle
onMounted(() => {
  fetchItems();
});
</script>

<template>
  <div>
    <h1>{{ title }} ({{ filteredItems.length }})</h1>
    <input v-model="searchQuery" placeholder="Search..." />
    <div v-if="isLoading">Loading...</div>
    <ul v-else>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
        <button @click="emit('delete', item.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>
```

## Reactivity: ref vs reactive

```typescript
import { ref, reactive, toRefs } from 'vue';

// ref  -  for primitives and single values (unwraps in template)
const count = ref(0);
count.value++; // need .value in script
// <template>{{ count }}</template>  -  no .value needed

// reactive  -  for objects (deep reactive, no .value needed)
const state = reactive({
  name: '',
  email: '',
  preferences: { theme: 'light', language: 'en' },
});
state.name = 'John'; // direct property access

// toRefs  -  destructure reactive object without losing reactivity
const { name, email } = toRefs(state);
// name is Ref<string>, tracks state.name

// RULE: Use ref for everything. Use reactive only for local form state.
```

## Watchers

```typescript
import { ref, watch, watchEffect } from 'vue';

const searchQuery = ref('');
const selectedCategory = ref('all');
const results = ref([]);

// watch  -  explicit source, access old/new values
watch(searchQuery, async (newQuery, oldQuery) => {
  if (newQuery.length >= 3) {
    results.value = await search(newQuery);
  }
}, { debounce: 300 }); // Vue 3.5+ debounce option

// Watch multiple sources
watch(
  [searchQuery, selectedCategory],
  ([query, category], [prevQuery, prevCategory]) => {
    fetchResults(query, category);
  }
);

// watchEffect  -  auto-tracks dependencies, runs immediately
watchEffect(async () => {
  // Automatically re-runs when searchQuery.value or selectedCategory.value changes
  if (searchQuery.value.length >= 3) {
    results.value = await search(searchQuery.value, selectedCategory.value);
  }
});

// Cleanup side effects
watchEffect((onCleanup) => {
  const controller = new AbortController();
  fetchData(searchQuery.value, { signal: controller.signal });
  onCleanup(() => controller.abort());
});

// watch with immediate + deep
watch(
  () => props.config,
  (newConfig) => { applyConfig(newConfig); },
  { immediate: true, deep: true }
);
```

## Composables (useXxx Pattern)

```typescript
// composables/useFetch.ts
import { ref, type Ref } from 'vue';

interface UseFetchReturn<T> {
  data: Ref<T | null>;
  error: Ref<string | null>;
  isLoading: Ref<boolean>;
  execute: () => Promise<void>;
}

export function useFetch<T>(url: string | Ref<string>): UseFetchReturn<T> {
  const data = ref<T | null>(null) as Ref<T | null>;
  const error = ref<string | null>(null);
  const isLoading = ref(false);

  async function execute() {
    isLoading.value = true;
    error.value = null;
    try {
      const resolvedUrl = typeof url === 'string' ? url : url.value;
      const response = await fetch(resolvedUrl);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      data.value = await response.json();
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Unknown error';
    } finally {
      isLoading.value = false;
    }
  }

  return { data, error, isLoading, execute };
}

// composables/useLocalStorage.ts
import { ref, watch, type Ref } from 'vue';

export function useLocalStorage<T>(key: string, defaultValue: T): Ref<T> {
  const stored = localStorage.getItem(key);
  const data = ref<T>(stored ? JSON.parse(stored) : defaultValue) as Ref<T>;

  watch(data, (newValue) => {
    localStorage.setItem(key, JSON.stringify(newValue));
  }, { deep: true });

  return data;
}

// composables/useDebounce.ts
import { ref, watch, type Ref } from 'vue';

export function useDebounce<T>(source: Ref<T>, delay = 300): Ref<T> {
  const debounced = ref(source.value) as Ref<T>;
  let timeout: ReturnType<typeof setTimeout>;

  watch(source, (newValue) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      debounced.value = newValue;
    }, delay);
  });

  return debounced;
}
```

## Pinia State Management

```typescript
// stores/auth.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null);
  const token = ref<string | null>(null);

  // Getters
  const isAuthenticated = computed(() => !!token.value);
  const displayName = computed(() => user.value?.name ?? 'Guest');

  // Actions
  async function login(credentials: { email: string; password: string }) {
    const response = await api.post('/auth/login', credentials);
    user.value = response.user;
    token.value = response.token;
  }

  function logout() {
    user.value = null;
    token.value = null;
  }

  return { user, token, isAuthenticated, displayName, login, logout };
}, {
  persist: true, // pinia-plugin-persistedstate
});

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

  const totalItems = computed(() =>
    items.value.reduce((sum, item) => sum + item.quantity, 0)
  );

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

  function addItem(product: Product) {
    const existing = items.value.find((i) => i.productId === product.id);
    if (existing) {
      existing.quantity++;
    } else {
      items.value.push({ productId: product.id, name: product.name, price: product.price, quantity: 1 });
    }
  }

  function removeItem(productId: string) {
    items.value = items.value.filter((i) => i.productId !== productId);
  }

  return { items, totalItems, totalPrice, addItem, removeItem };
});
```

## Vue Router 4

```typescript
// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    children: [
      { path: '', name: 'home', component: () => import('@/pages/HomePage.vue') },
      { path: 'about', name: 'about', component: () => import('@/pages/AboutPage.vue') },
    ],
  },
  {
    path: '/dashboard',
    component: () => import('@/layouts/DashboardLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'dashboard', component: () => import('@/pages/DashboardPage.vue') },
      { path: 'settings', name: 'settings', component: () => import('@/pages/SettingsPage.vue') },
      { path: 'users/:id', name: 'user-detail', component: () => import('@/pages/UserDetailPage.vue'), props: true },
    ],
  },
  { path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('@/pages/NotFoundPage.vue') },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition ?? { top: 0 };
  },
});

// Navigation guard
router.beforeEach((to, from) => {
  const auth = useAuthStore();
  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return { name: 'login', query: { redirect: to.fullPath } };
  }
});

export default router;
```

## Do's

- Use `<script setup lang="ts">` for all new components
- Use `ref()` as the default reactive primitive
- Extract reusable logic into composables (useXxx)
- Use Pinia with Composition API syntax (`defineStore` with setup function)
- Use `defineModel` for two-way binding in custom components
- Type props and emits with TypeScript generics
- Use `watchEffect` when you want automatic dependency tracking
- Lazy-load routes with dynamic imports

## Don'ts

- Do not use Options API for new code (Composition API is the standard)
- Do not mutate props directly; emit events to parent
- Do not use `reactive()` for primitives; use `ref()`
- Do not destructure `reactive()` objects without `toRefs()`
- Do not forget `.value` in script when using `ref()`
- Do not use Vuex for new projects; use Pinia
- Do not put business logic in components; extract to composables
- Do not use `this` in `<script setup>` (there is no `this`)

## Troubleshooting

| Problem | Cause | Solution |
|---------|-------|----------|
| Reactivity lost after destructure | Destructured reactive object | Use `toRefs()` or keep using the reactive object directly |
| Component not updating | Replacing reactive object reference | Mutate properties instead, or use `ref()` |
| Watch not triggering | Watching wrong source | Watch `() => state.prop` for reactive properties |
| Prop mutation warning | Modifying prop directly | Use `defineModel` or emit event with new value |
| Template ref is null | Accessed before mount | Use `onMounted` hook or optional chaining |
| Pinia state lost on refresh | No persistence plugin | Add `pinia-plugin-persistedstate` |
