Files
2nd/10_Wiki/Topic_Programming/Frontend/Composition API.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

187 lines
4.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: wiki-2026-0508-composition-api
title: Composition API (Vue 3)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Vue Composition API, setup script]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [vue, composition-api, reactivity, frontend]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript
framework: Vue 3
---
# Composition API (Vue 3)
## 매 한 줄
> **"매 reactive primitive 으로 logic 을 조합한다"**. Composition API 는 Vue 3 의 `setup()` / `<script setup>` 기반 model — `ref`, `reactive`, `computed`, `watch` 를 직접 import 하여 매 logic 조각을 자유 조합, 매 Options API 의 `data/methods/computed` partition 을 대체.
## 매 핵심
### 매 핵심 primitives
- `ref(v)`: 매 wraps any value, `.value` access.
- `reactive(obj)`: deep proxy — object/array 만.
- `computed(fn)`: derived ref, lazy + cached.
- `watch(src, cb)`: explicit deps + cb.
- `watchEffect(fn)`: auto-track, eager.
- `effectScope()`: manual lifecycle group.
### 매 vs Options API
| Aspect | Options | Composition |
|---|---|---|
| Logic reuse | mixins (collision-prone) | composables (clean) |
| TypeScript | OK | excellent |
| File length scaling | grows by category | grows by feature |
| Learning curve | gentle | steeper but worth it |
### 매 `<script setup>` perks
- Top-level await.
- Auto-expose for template.
- `defineProps`, `defineEmits`, `defineModel`, `defineExpose` macros.
- Compile-time optimizations (no `setup()` boilerplate).
## 💻 패턴
### Basic setup with ref + computed
```vue
<script setup lang="ts">
import { ref, computed } from 'vue';
const count = ref(0);
const double = computed(() => count.value * 2);
const inc = () => count.value++;
</script>
<template>
<button @click="inc">{{ count }} (×2 = {{ double }})</button>
</template>
```
### Typed props + emits + v-model
```vue
<script setup lang="ts">
const props = defineProps<{ initial?: number }>();
const emit = defineEmits<{ change: [value: number] }>();
const model = defineModel<string>({ default: '' });
</script>
<template>
<input v-model="model" />
</template>
```
### reactive with toRefs (avoid losing reactivity)
```ts
import { reactive, toRefs } from 'vue';
export function useUser() {
const state = reactive({ name: 'Ada', age: 36 });
return { ...toRefs(state) }; // 매 destructurable + reactive
}
```
### watch with explicit source
```ts
import { ref, watch } from 'vue';
const query = ref('');
watch(query, async (q, _old, onCleanup) => {
const ctrl = new AbortController();
onCleanup(() => ctrl.abort());
const r = await fetch(`/search?q=${q}`, { signal: ctrl.signal });
// ...
});
```
### watchEffect (auto-track)
```ts
import { ref, watchEffect } from 'vue';
const userId = ref(1);
watchEffect(async () => {
const r = await fetch(`/api/users/${userId.value}`);
user.value = await r.json();
});
```
### Provide / inject (typed)
```ts
// keys.ts
import type { InjectionKey, Ref } from 'vue';
export const ThemeKey: InjectionKey<Ref<'light' | 'dark'>> = Symbol('theme');
// Parent
import { provide, ref } from 'vue';
const theme = ref<'light' | 'dark'>('dark');
provide(ThemeKey, theme);
// Child
import { inject } from 'vue';
const theme = inject(ThemeKey)!;
```
### Async setup with Suspense
```vue
<!-- Parent -->
<Suspense>
<UserProfile :id="42" />
<template #fallback><Skeleton /></template>
</Suspense>
<!-- UserProfile.vue -->
<script setup lang="ts">
const props = defineProps<{ id: number }>();
const user = await (await fetch(`/users/${props.id}`)).json();
</script>
```
### Lifecycle hooks
```ts
import { onMounted, onUnmounted } from 'vue';
onMounted(() => console.log('mounted'));
onUnmounted(() => console.log('cleanup'));
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| New Vue 3 project | Composition + `<script setup>` |
| Migrating from Vue 2 | Options 유지 → 점진 conversion |
| Logic reuse needed | Composable function |
| Simple 1-off component | Either OK, prefer setup for TS |
**기본값**: `<script setup>` + Composition API. Options API 는 legacy maintenance only.
## 🔗 Graph
- 부모: [[Vue 3]]
- 변형: [[Vue Options API]] · [[Solid-Signals]]
- 응용: [[Composables]] · [[Pinia]] · [[Nuxt]]
- Adjacent: [[Component-Composition]] · [[TypeScript]]
## 🤖 LLM 활용
**언제**: Vue 3 component 작성, composable 추출, TS 강한 typing 필요.
**언제 X**: Vue 2.7 이전 — 매 backport limited.
## ❌ 안티패턴
- **Mixing reactive() destructure without toRefs**: loses reactivity silently.
- **Using `ref.value` in template**: 매 unwrap 자동, `.value` 의 X.
- **Excessive `watch`**: 매 computed 로 충분한 경우 매 prefer computed.
## 🧪 검증 / 중복
- Verified (vuejs.org official guide).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Composition API primitives + setup patterns |