시작하기
Hello World와 주석
Vue 3 앱은 createApp()으로 시작해 DOM 요소에 mount()합니다. 보간은 이중 중괄호 {{ }}로 반응형 데이터를 렌더링합니다. HTML 주석은 렌더링된 DOM에 나타납니다. DOM에 남지 않는 주석이 필요하면 <script> 블록 안에서 /* */를 사용하세요.
<!-- index.html -->
<div id="app">
<p>{{ message }}</p>
<!-- This is an HTML comment, visible in DOM -->
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data() {
return { message: 'Hello Vue 3!' }
}
}).mount('#app')
</script>SFC 구조(단일 파일 컴포넌트)
SFC는 템플릿, 스크립트, 스타일을 하나의 .vue 파일에 묶습니다. <script setup>은 Composition API의 권장 문법으로 간결하고 상용구가 없습니다. scoped 스타일은 현재 컴포넌트에만 적용되어 누출을 막습니다. 각 SFC는 JavaScript 모듈로 컴파일됩니다.
<template>
<button @click="count++">Count: {{ count }}</button>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<style scoped>
button { color: #42B883; }
</style>앱 인스턴스와 마운트
createApp은 자기 범위의 애플리케이션 인스턴스를 반환합니다. 전역 Vue 상태가 없어 한 페이지에 독립적인 앱 여러 개를 마운트할 수 있습니다. 플러그인 등록, 전역 값 제공, config 설정은 mount() 호출 전에 하세요. 마운트 후에는 추가 config 변경이 적용되지 않습니다.
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// global config / plugins before mounting
app.config.errorHandler = (err) => console.error(err)
app.provide('apiKey', '12345')
app.mount('#app')프로젝트 스캐폴딩(Vite)
npm create vue@latest는 공식 스캐폴딩 도구로 TypeScript, Router, Pinia, Vitest 설정을 선택할 수 있습니다. Vite를 사용해 개발 서버가 즉시 시작되고 HMR이 동작합니다. Vue의 의견이 없는 최소 템플릿을 원하면 하위 수준 도구인 create-vite를 사용하세요.
# scaffold a new Vue project with Vite
npm create vue@latest my-app
cd my-app
npm install
npm run dev # start dev server (HMR)
npm run build # production build to /dist
# or with create-vite directly
npm create vite@latest my-app -- --template vue-tsdefineOptions와 defineProps
defineProps, defineEmits, defineOptions는 컴파일 타임 매크로라 가져올 필요가 없습니다. defineProps는 런타임 검증과 함께 컴포넌트의 prop 계약을 선언합니다. defineOptions는 name, inheritAttrs 등 <script setup>에서 직접 표현할 수 없는 옵션을 설정합니다.
<script setup>
// declare props with types and defaults
const props = defineProps({
title: String,
count: { type: Number, default: 0 }
})
// declare emits
const emit = defineEmits(['update', 'delete'])
// additional non-reactive options
defineOptions({ name: 'MyButton', inheritAttrs: false })
</script>템플릿 문법
텍스트 보간
{{ }}는 텍스트를 안전하게(HTML 이스케이프) 렌더링합니다. v-once는 정적 콘텐츠의 바인딩을 첫 렌더 후 동결합니다. v-html은 원시 HTML을 주입하므로 XSS를 피하려면 신뢰할 수 있는 콘텐츠에만 사용하세요. {{ }} 안에는 모든 단일 JavaScript 표현식을 쓸 수 있지만 할당이나 var 선언 같은 문장은 안 됩니다.
<template>
<p>{{ message }}</p>
<!-- renders the value of message -->
<!-- one-time binding (no updates after render) -->
<span v-once>{{ initialCount }}</span>
<!-- raw HTML (sanitize to avoid XSS!) -->
<div v-html="rawHtmlContent"></div>
<!-- expressions are supported -->
<p>{{ count * 2 }}</p>
<p>{{ isReady ? 'Yes' : 'No' }}</p>
<p>{{ message.split('').reverse().join('') }}</p>
</template>속성 바인딩
v-bind(단축 :)는 속성을 반응형으로 바인딩합니다. class에는 객체(참인 키 적용), 배열, 문자열을 넘길 수 있습니다. style은 camelCase나 kebab-case 키의 객체를 받습니다. 동적 인자 문법 :[expr]은 속성 이름 자체를 반응형으로 만들어 이벤트 이름이나 지역화 속성에 유용합니다.
<template>
<!-- bind an attribute -->
<img v-bind:src="imageUrl" />
<img :src="imageUrl" /> <!-- shorthand -->
<!-- bind class -->
<div :class="{ active: isActive, error: hasError }"></div>
<div :class="['btn', isActive && 'active']"></div>
<!-- bind style -->
<div :style="{ color: textColor, fontSize: size + 'px' }"></div>
<!-- dynamic attribute name -->
<button :[eventName]="handler">Click</button>
</template>불리언 및 다중 값 속성
disabled나 checked 같은 불리언 속성은 값이 참일 때만 Vue가 속성을 렌더링합니다. class와 style은 특별히 정적 값과 바인딩 값을 대체하지 않고 병합합니다. 폼 입력에는 :value와 @input을 수동 바인딩하기보다 v-model을 권장합니다.
<template>
<!-- boolean attribute: presence depends on value -->
<input :disabled="isDisabled" />
<button :disabled="!canSubmit">Submit</button>
<!-- class merging: bound class merges with static class -->
<div class="card" :class="{ highlighted: isFeatured }"></div>
<!-- style merging: bound style merges with static style -->
<div style="color: red" :style="{ fontSize: '14px' }"></div>
<!-- form attributes: value is bound with v-model instead -->
<input v-model="text" />
</template>수정자와 표현식
수정자는 점으로 표시되는 접미사로 특별 처리를 뜻합니다. 이벤트 수정자(.prevent, .stop, .once, .self)는 핸들러를 해당 DOM 메서드로 감쌉니다. 키 수정자(.enter, .esc, .ctrl)는 키로 이벤트를 필터링합니다. v-model 수정자(.trim, .number, .lazy)는 할당 전에 입력 값을 변환합니다.
<template>
<!-- .prevent calls event.preventDefault() -->
<form @submit.prevent="onSubmit">...</form>
<!-- .stop calls event.stopPropagation() -->
<button @click.stop="doStuff">Click</button>
<!-- .once runs handler only one time -->
<button @click.once="init">Init</button>
<!-- .trim and .lazy modifiers on v-model -->
<input v-model.trim="email" />
<input v-model.lazy="text" />
<!-- chain multiple modifiers -->
<input @keyup.enter.ctrl="onCombo" />
</template>템플릿 ref
템플릿 ref는 DOM 요소에 직접 접근하게 합니다. ref 속성과 같은 이름의 ref()를 선언하면 Vue가 마운트 후 DOM 노드를 할당합니다. onMounted(또는 이후)에서 접근하세요. 마운트 전에는 ref가 null입니다. v-for에서는 ref가 요소 배열이 됩니다. 반응형 데이터 흐름으로 충분하면 ref를 피하세요.
<script setup>
import { ref, onMounted } from 'vue'
// declare a ref matching the template ref attribute
const inputEl = ref(null)
onMounted(() => {
// access the DOM node after mount
inputEl.value.focus()
})
</script>
<template>
<input ref="inputEl" />
</template>디렉티브
v-if / v-else-if / v-else
v-if는 조건부로 요소를 렌더링하며 DOM에서 추가/제거합니다. v-else-if와 v-else는 앞선 v-if와 연결됩니다. 추가 래퍼 요 소를 원하지 않으면 여러 요소를 <template v-if>로 감싸세요. v-if는 토글 비용(DOM 생성)이 높지만 조건이 거짓일 때 초기 비용은 v-show보다 낮습니다.
<template>
<div v-if="type === 'A'">Type A</div>
<div v-else-if="type === 'B'">Type B</div>
<div v-else-if="type === 'C'">Type C</div>
<div v-else>Unknown type</div>
<!-- use <template> for invisible wrapper -->
<template v-if="showHeader">
<h1>Title</h1>
<p>Subtitle</p>
</template>
</template>v-show vs v-if
조건이 거의 바뀌지 않으면 v-if를 사용하세요. 요소가 파괴/재생성되어 숨겨졌을 때 렌더 비용을 절약합니다. 자주 토글하는 요소(탭, 드롭다운)에는 v-show를 사용하세요. 요소가 DOM에 남고 display:none만 토글되어 토글이 저렴합니다. v-show는 <template>이나 v-else와 동작하지 않습니다.
<template>
<!-- v-if removes from DOM when false -->
<p v-if="isVisible">I'm created/destroyed</p>
<!-- v-show just toggles display:none -->
<p v-show="isVisible">I'm always in DOM, just hidden</p>
</template>
<script setup>
import { ref } from 'vue'
const isVisible = ref(true)
</script>v-for와 :key
v-for는 배열, 객체, 숫자 범위를 반복합니다. :key 속성은 추적 항등성에 필수입니다. 재정렬 중 Vue가 DOM 노드를 효율적으로 재사용하게 합니다. 안정적인 고유 id를 key로 사용하고 배열 인덱스는 절대 쓰지 마세요(항목 이동 시 깨짐). 같은 요소에서 v-for가 v-if보다 우선순위가 높으므로 둘을 함께 쓰지 마세요.
<template>
<!-- iterate over array -->
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
<!-- iterate with index -->
<li v-for="(item, index) in items" :key="item.id">
{{ index }}: {{ item.name }}
</li>
<!-- iterate over object -->
<li v-for="(value, key) in user" :key="key">
{{ key }}: {{ value }}
</li>
<!-- range (1 to n) -->
<span v-for="n in 10" :key="n">{{ n }}</span>
</template>v-model 바인딩
v-model은 폼 입력의 양방향 바인딩으로 입력 값을 반응형 상태와 동기화합니다. 체크박스 하나는 불리언에 바인딩되고 같은 v-model을 공유 하는 여러 체크박스는 선택된 값 배열에 바인딩됩니다. 수정자: .lazy(input 대신 change에서 동기화), .number(숫자로 캐스트), .trim(공백 제거).
<template>
<!-- text input -->
<input v-model="text" />
<!-- multi-line textarea -->
<textarea v-model="message"></textarea>
<!-- checkbox (single = boolean, multiple = array) -->
<input type="checkbox" v-model="isChecked" />
<input type="checkbox" value="apple" v-model="fruits" />
<input type="checkbox" value="banana" v-model="fruits" />
<!-- radio -->
<input type="radio" value="A" v-model="picked" />
<!-- select -->
<select v-model="selected">
<option value="a">A</option>
<option value="b">B</option>
</select>
</template>커스텀 디렉티브
커스텀 디렉티브는 DOM 요소를 직접 조작하게 합니다. <script setup>에서 vSomething(camelCase) 이름의 변수는 템플릿에서 v-something으로 자동 사용 가능합니다. 디렉티브 객체에는 mounted, updated, unmounted 등 수명 주기 훅이 있습니다. 반응성이 필요하면 디렉티브보다 컴포넌트를 선호하세요. 디렉티브는 포커스, 툴팁, 드래그 같은 저수준 DOM 작업용입니다.
<script setup>
// local directive: function form (mounted + updated)
const vFocus = {
mounted: (el) => el.focus()
}
// global registration
// app.directive('focus', { mounted: el => el.focus() })
</script>
<template>
<input v-focus />
</template>계산된 속성
기본 computed
computed는 의존성이 바뀔 때만 다시 평가하는 캐시된 getter를 만듭니다. 메서드 호출과 달리 의존성이 갱신될 때까지 반복 접근이 캐시 값을 반환합니다. <script>에서는 .value로 접근하고 템플릿에서는 Vue가 자동 언랩합니다. 값이 반응형 상태에 의존하면 메서드보다 computed를 사용하세요. 더 빠르고 선언적입니다.
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
// computed caches based on dependencies
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
// access via .value in script
console.log(fullName.value) // 'John Doe'
</script>
<template>
<!-- use without .value in template -->
<p>{{ fullName }}</p>
</template>쓰기 가능한 computed
기본적으로 computed는 읽기 전용이지만 getter와 setter를 제공할 수 있습니다. setter는 .value에 할 당할 때 호출됩니다. 파생 상태의 양방향 바인딩(예: full-name 입력을 first/last name 필드로 동기화)에 유용합니다. 무한 루프를 피하세요. setter가 자신을 다시 트리거하는 방식으로 computed의 의존성을 직접 설정하면 안 됩니다.
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})
// assignment triggers the setter
fullName.value = 'Jane Smith'
</script>computed vs 메서드
computed 속성은 의존성에 따라 결과를 캐시하고 items가 바뀔 때만 다시 실행됩니다. 메서드는 무엇이 바뀌든 모든 렌더에서 다시 실행됩니다. 반응형 상태에서 파생된 값에는 computed를, 매개변수를 받거나 부수 효과가 있는 동작에는 메서드를 사용하세요. computed는 '이 값은 파생됨' 대 '이 일을 함'처럼 의도를 더 명확히 합니다.
<script setup>
import { ref, computed } from 'vue'
const items = ref([1, 2, 3, 4, 5])
// computed: cached, re-runs only if items changes
const doubled = computed(() =>
items.value.map(x => x * 2)
)
// method: re-runs on every render
function getDoubled() {
return items.value.map(x => x * 2)
}
</script>
<template>
<!-- cached, no recompute on unrelated re-renders -->
<p>{{ doubled }}</p>
<!-- re-invoked on every render -->
<p>{{ getDoubled() }}</p>
</template>computed getter 함정
computed getter는 순수해야 합니다. 부수 효과(변경, 비동기, fetch)가 없어야 합니다. Date.now()나 Math.random()을 호출하지 마세요. 반응형이 아니라 computed가 갱신되지 않습니다. 부수 효과가 필요하면 워처를 사용하세요. 비동기가 필요하면 computed는 await하지 않으므로 watch + ref나 Suspense가 있는 async setup을 사용하세요.
<script setup>
import { ref, computed } from 'vue'
const date = ref(new Date())
// BAD: non-reactive Date.now() — won't update
const badTime = computed(() => Date.now())
// BAD: side effect inside computed
const count = ref(0)
const bad = computed(() => {
count.value++ // never mutate state in computed!
return count.value
})
// GOOD: pure function of reactive state
const formatted = computed(() =>
date.value.toLocaleDateString()
)
</script>Options API의 computed
Options API에서는 computed 옵션에 선언합니다. this.total로 접근하며(.value도 괄호도 없음) Vue가 자동 언랩합니다. 쓰기 가능한 computed는 get/set 함수를 씁니다. computed 속성은 data, methods와 함께 컴포넌트 인스턴스에 노출되어 모두 this로 접근할 수 있습니다.
<script>
export default {
data() {
return { price: 100, quantity: 2 }
},
computed: {
total() {
return this.price * this.quantity
},
discounted: {
get() { return this.total * 0.9 },
set(v) { this.price = v / 0.9 / this.quantity }
}
},
methods: {
checkout() { console.log(this.total) }
}
}
</script>워처
기본 watch
watch는 감시 대상이 바뀔 때 콜백을 실행합니다. 대상은 ref, reactive 객체의 속성(getter 경유), 또는 소스 배열이 될 수 있습니다. 콜백은 (newValue, oldValue)를 받습니다. 중첩 반응형 속성을 감시하려면 getter () => x.y를 사용하세요. 워처는 부수 효과(fetch, 로그, 저장)용이며 상태 파생에는 computed를 사용하세요.
<script setup>
import { ref, watch } from 'vue'
const question = ref('')
// watch a ref
watch(question, (newValue, oldValue) => {
console.log('changed from', oldValue, 'to', newValue)
})
// watch a getter (computed source)
watch(
() => question.value.length,
(newLen) => {
if (newLen > 100) console.warn('Too long!')
}
)
</script>깊은 감시와 즉시 실행
deep: true는 객체의 모든 중첩 속성 변경에서 watch가 발생하게 하므로 유용하지만 큰 구조에서는 비쌉니다. immediate: true는 설정 시 콜백을 즉시 실행합니다(첫 호출에서 oldValue는 undefined). 거대한 객체의 깊은 감시는 피하고 성능을 위해 특정 getter () => obj.specificField를 감시하세요.
<script setup>
import { reactive, watch } from 'vue'
const user = reactive({
name: 'Alice',
address: { city: 'NYC', zip: '10001' }
})
// deep: watch nested property changes
watch(
() => user.address,
(newAddr) => console.log('address changed', newAddr),
{ deep: true }
)
// immediate: run callback right away
watch(
user,
(val) => saveToServer(val),
{ deep: true, immediate: true }
)
</script>watchEffect(자동 추적)
watchEffect는 콜백을 즉시 실행하고 내부에서 접근한 반응형 의존성을 자동 추적합니다. 추적된 의존성이 바뀔 때마다 콜백이 다시 실행됩니다. watch와 달리 소스를 지정하지 않고 추론됩니다. oldValue가 필요 없고 자동 의존성 추적을 원할 때 watchEffect를 사용하세요. 여러 반응형 소스를 읽는 구독 설정에 유용합니다.
<script setup>
import { ref, watchEffect } from 'vue'
const a = ref(1)
const b = ref(2)
// runs immediately and tracks dependencies automatically
watchEffect(() => {
console.log('a + b =', a.value + b.value)
})
// logs: a + b = 3
a.value = 10 // logs: a + b = 12
// stop the watcher
const stop = watchEffect(() => { /* ... */ })
stop() // cleanup
</script>watch vs watchEffect
oldValue, 지연 실행(초기 실행 건너뛰기), 특정 소스의 명시적 감시가 필요하면 watch를 선택하세요. 즉시 실행, oldValue 불필요, 여러 반응형 값을 건드리는 부수 효과의 자동 추적이 필요하면 watchEffect를 선택하세요. 배열 소스를 쓰는 watch는 콜백에서 새/이전 값 배열을 받습니다.
<script setup>
import { ref, watch, watchEffect } from 'vue'
const count = ref(0)
// watch: lazy, explicit source, has oldValue
watch(count, (newVal, oldVal) => {
console.log('count changed:', oldVal, '->', newVal)
})
// watchEffect: eager, auto-tracked, no oldValue
watchEffect(() => {
console.log('count is', count.value)
})
// logs immediately: count is 0
// watch multiple sources
const a = ref(1), b = ref(2)
watch([a, b], ([newA, newB], [oldA, oldB]) => {
console.log('a or b changed')
})
</script>워처 정리와 flush
onCleanup 콜백(세 번째 인자)은 다음 워처 호출 전에 실행되는 정리 함수를 등록하므로 진행 중인 요청 취소, 타이머 해제, 구독 해지에 완벽합니다. flush: 'post'는 Vue가 DOM을 갱신한 후 워처를 실행합니다(갱신된 DOM을 읽을 때 유용). 'sync'는 의존성 변경 시 동기 실행이며 드물게 필요하고 성능 문제를 일으킬 수 있습니다.
<script setup>
import { ref, watch } from 'vue'
const id = ref(1)
// cleanup function: runs before next callback
watch(id, (newId, oldId, onCleanup) => {
const controller = new AbortController()
fetch(`/api/user/${newId}`, { signal: controller.signal })
.then(r => r.json())
// cancel previous request when id changes again
onCleanup(() => controller.abort())
}, { flush: 'post' })
// flush: 'pre' (default) | 'post' (after DOM update) | 'sync'
</script>조건부 렌더링
v-if vs v-show
v-if는 실제로 요소를 DOM에 추가/제거하므로 초기 비용이 높지만 숨겨졌을 때 비용이 0입니다. v-show는 항상 요소를 렌더링하고 display:none을 토글하므로 토글이 저렴하지만 숨겨져도 요소가 존재합니다. 거의 바뀌지 않는 조건(또는 숨은 요소가 아예 없어야 할 때)에는 v-if를, 탭/드롭다운/모달처럼 자주 토글하는 UI에는 v-show를 사용하세요.
<template>
<!-- v-if: element removed from DOM when false -->
<div v-if="isLoggedIn">Welcome back</div>
<!-- v-show: element stays, display toggles -->
<div v-show="isLoggedIn">Welcome back</div>
</template>
<!-- v-show compiles to: -->
<!-- <div style="display: none;">Welcome back</div> when false -->
<!-- v-if does not render the element at all when false -->v-if와 v-else 체인
v-else-if와 v-else는 v-if(또는 다른 v-else-if) 요소 바로 뒤에 와야 하며 사이에 다른 요소가 있으면 안 됩니다. 체인은 위에서 아래로 평가되고 첫 참 조건에서 멈춥니다. 마지막 v-else가 나머지 모든 경우를 잡습니다. 상태 기반 UI(로딩, 오류, 빈 상태, 성공)에 좋은 패턴입니다.
<template>
<div v-if="status === 'loading'">Loading...</div>
<div v-else-if="status === 'error'">Error occurred</div>
<div v-else-if="status === 'empty'">No items</div>
<div v-else>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>v-if용 <template> 래퍼
<template>은 DOM에 렌더링되지 않는 논리 래퍼로, 추가 HTML 없이 여러 요소를 하나의 v-if나 v-for 아래 묶는 데 완벽합니다. 마크업이 의미적으로 유지됩니다(불필요한 div 없음). template에 v-for를 쓸 때는 template 요소 자체에 :key가 필요합니다.
<template>
<!-- group elements under one condition, no wrapper div -->
<template v-if="showProfile">
<h2>{{ user.name }}</h2>
<p>{{ user.bio }}</p>
<button @click="edit">Edit</button>
</template>
<!-- combine v-if with v-for on template -->
<template v-for="item in items" :key="item.id">
<dt>{{ item.term }}</dt>
<dd>{{ item.def }}</dd>
</template>
</template>v-if vs v-for 우선순위
같은 요소에 v-if와 v-for를 절대 함께 쓰지 마세요. Vue 3에서 v-if가 우선순위가 높아 v-for보다 먼저 실행되므로 루프 변수를 아직 쓸 수 없어 오류가 납니다. 대신 computed 속성으로 배열을 필터링하거나(권장) 인라인 .filter()를 사용하세요. 꼭 필요하면 감싸는 <template v-for>와 내부 v-if를 사용하세요.
<template>
<!-- AVOID: v-if and v-for on same element -->
<!-- In Vue 3, v-if has higher priority than v-for -->
<!-- so 'item' is not defined when v-if evaluates -->
<li v-for="item in items" v-if="item.active" :key="item.id">
{{ item.name }}
</li>
<!-- GOOD: filter first, then iterate -->
<li
v-for="item in items.filter(i => i.active)"
:key="item.id"
>
{{ item.name }}
</li>
<!-- BEST: use computed for the filtered list -->
</template>v-if와 Transition
v-if(또는 v-show) 요소를 <Transition>으로 감싸 enter/leave를 애니메이션하세요. Vue는 적절한 시점에 v-enter-from, v-enter-active, v-enter-to(그리고 v-leave-*) 클래스를 추가합니다. 이 클래스에 CSS 전환을 정의하세요. name='fade'는 'v-' 접두사를 'fade-'로 바꿉니다. Transition은 단일 자식 요소만 지원하므로 목록에는 TransitionGroup을 사용하세요.
<template>
<Transition name="fade">
<p v-if="show">Hello</p>
</Transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>목록 렌더링
배열과 v-for
v-for는 배열을 반복하며 각 항목과 (선택적으로) 인덱스를 노출합니다. :key는 item.id 같은 안정적인 고유 값에 항상 바인딩하세요. 재정렬 중 Vue가 이전/새 노드를 매칭해 컴포넌트 상태와 DOM을 효율적으로 보존합니다. 인덱스를 key로 쓰면 항목 삽입/제거/재정렬 시 깨져 미묘한 버그가 생깁니다.
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
])
</script>
<template>
<!-- always provide :key with stable unique id -->
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
<!-- with index (avoid as :key) -->
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }}. {{ item.name }}
</li>
</template>객체와 범위의 v-for
객체에 v-for를 쓰면 기본적으로 값을 반복하며 두 번째 인자는 키, 세 번째는 인덱스입니다. 객체 반복 순서는 Object.keys()(문자열 키는 삽입 순서)를 따릅니다. 숫자 n의 v-for는 1부터 n까지(포함, 0부터 n-1이 아님) 반복합니다. 필터링/정렬 목록에는 가독성과 캐싱을 위해 인라인 로직보다 computed 속성을 선호하세요.
<template>
<!-- iterate object: (value, key, index) -->
<div v-for="(value, key, index) in user" :key="key">
{{ index }}. {{ key }}: {{ value }}
</div>
<!-- iterate a number range (1 to n inclusive) -->
<span v-for="n in 10" :key="n">{{ n }} </span>
<!-- 1 2 3 4 5 6 7 8 9 10 -->
<!-- use v-for of computed for derived lists -->
<li v-for="todo in doneTodos" :key="todo.id">
{{ todo.text }}
</li>
</template>목록 변경 감지
Vue 3는 Proxy 기반 반응성을 쓰므로 push, pop, splice, sort, reverse로 배열을 변경해도 모두 갱신을 트리거합니다(Vue 2와 달리 특별한 주의점 없음). 전체 배열 교체(items.value = newArray)도 ref의 값 setter가 반응성을 트리거해 동작합니다. filter/map은 새 배열을 만들므로 갱신하려면 다시 할당하세요.
<script setup>
import { ref } from 'vue'
const items = ref([1, 2, 3])
// MUTATION methods (Vue 3 detects these via Proxy)
items.value.push(4) // add
items.value.pop() // remove last
items.value.splice(1, 1) // remove at index
items.value.sort() // sort
// REPLACEMENT (always reactive)
items.value = items.value.filter(n => n > 1)
items.value = [...items.value, 5]
</script>목록용 TransitionGroup
TransitionGroup은 v-for 목록의 enter, leave, move(항목 위치 변경 시)를 애니메이션합니다. Transition과 달리 실제 요소를 렌더링합니다(tag로 설정). 각 자식에는 고유한 :key가 필수입니다. .list-move 클래스는 목록 재정렬 시 항목이 새 위치로 미끄러지는 애니메이션을 합니다. 순수 CSS로는 불가능한 세련된 효과입니다. 부드러운 이동을 위해 leave-active에는 position: absolute가 필요합니다.
<template>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</TransitionGroup>
</template>
<style>
.list-enter-active, .list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from, .list-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* animate items moving to new positions */
.list-move {
transition: transform 0.5s ease;
}
</style>성능: v-memo
v-memo는 최적화 힌트입니다. 의존성 배열의 값 중 하나가 바뀌지 않으면 Vue가 요소 재렌더링을 건너뜁니다. 각 갱신에서 대부분 항목이 바뀌지 않는 큰 목록에서 재렌더링을 크게 줄일 수 있습니다. 성능 문제를 측정한 뒤에만 사용하세요. 조기 최적화는 복잡성과 오래된 UI 위험을 더합니다.
<template>
<!-- skip re-render of this item unless 'id' or 'selected' changes -->
<div
v-for="item in hugeList"
:key="item.id"
v-memo="[item.id, item.id === selectedId]"
>
{{ item.name }} — {{ item.id === selectedId ? '★' : '' }}
</div>
</template>이벤트 처리
인라인 핸들러
@click(v-on:click의 단축)은 클릭 핸들러를 바인딩합니다. 인라인 문장(count++)은 단순한 경우에 동작합니다. 메서드 이름(greet)은 첫 인자로 네이티브 이벤트를 자동으로 받습니다. 사용자 정의 인자와 이벤트를 모두 넘기려면 $event와 함께 메서드를 명시 호출하세요: greet('hi', $event).
<script setup>
import { ref } from 'vue'
const count = ref(0)
const name = ref('Vue')
function greet(event) {
alert('Hello ' + name.value)
// event is the native DOM event
console.log(event.target.tagName)
}
</script>
<template>
<!-- inline statement -->
<button @click="count++">Add</button>
<!-- method reference (auto-receives event) -->
<button @click="greet">Greet</button>
<!-- call with custom args (use $event for native event) -->
<button @click="greet($event)">Greet</button>
</template>이벤트 수정자
이벤트 수정자는 이벤트 이름 뒤에 점으로 연결합니다. .prevent와 .stop이 가장 흔합니다(폼 제출, 이벤트 버블링). .self는 요소 자체(자식이 아님)가 클릭될 때만 핸들러가 발생하게 합니다. .passive는 핸들러가 preventDefault를 호출하지 않음을 브라우저에 알려 스크롤을 부드럽게 하므로 터치/스크롤 핸들러에 중요합니다.
<template>
<!-- .prevent: call preventDefault() -->
<form @submit.prevent="onSubmit">...</form>
<!-- .stop: call stopPropagation() -->
<div @click="outer">
<button @click.stop="inner">Won't bubble</button>
</div>
<!-- .self: only trigger if event.target === current element -->
<div @click.self="onSelf">Only direct clicks</div>
<!-- .once: handler removed after first invocation -->
<button @click.once="init">Init once</button>
<!-- .capture: use capture phase instead of bubble -->
<div @click.capture="onCapture">...</div>
<!-- .passive: improve scroll perf (no preventDefault) -->
<div @scroll.passive="onScroll">...</div>
</template>키와 시스템 수정자
키 수정자는 키 이름으로 키보드 이벤트를 필터링합니다(.enter, .esc, .delete, .space, .tab, .up, .down, .left, .right). 시스템 수정자(.ctrl, .alt, .shift, .meta)는 해당 키가 눌려 있어야 합니다. .exact는 다른 시스템 수정자가 눌리지 않음을 보장하므로 @click.ctrl.exact는 Ctrl+Click에서만 발생하고 Ctrl+Shift+Click에서는 발생하지 않습니다. Vue가 별칭을 두지 않은 키(page-down)에는 kebab-case를 사용하세요.
<template>
<!-- key modifiers: only fire on specific keys -->
<input @keyup.enter="submit" />
<input @keyup.esc="cancel" />
<input @keyup.delete="remove" />
<!-- system modifiers: ctrl, alt, shift, meta -->
<button @click.ctrl="openInNewTab">Ctrl+Click</button>
<input @keyup.alt.enter="altEnter" />
<!-- .exact: no other modifiers can be pressed -->
<button @click.ctrl.exact="onCtrlOnly">Ctrl only</button>
<!-- any key code via kebab-case (deprecated but works) -->
<input @keyup.page-down="onPageDown" />
</template>emit으로 커스텀 이벤트
자식 컴포넌트는 이벤트를 emit해 위로 통신합니다. defineEmits는 이벤트 이름을 선언합니다(검증과 IDE 힌트에 사용). 부모는 @event-name으로 듣습니다. 페이로드는 emit에 추가 인자로 넘기고 부모 핸들러가 받습니다. 관례상 템플릿에서는 kebab-case 이벤트 이름(my-event), defineEmits에서는 camelCase(myEvent)를 쓰며 Vue가 자동 변환합니다.
<!-- ChildButton.vue -->
<script setup>
const emit = defineEmits(['increment', 'delete'])
function onClick() {
// emit with payload
emit('increment', 1)
}
</script>
<template>
<button @click="onClick">+1</button>
</template>
<!-- Parent.vue -->
<template>
<ChildButton @increment="onIncrement" @delete="remove" />
</template>
<script setup>
function onIncrement(amount) {
console.log('incremented by', amount)
}
</script>컴포넌트의 v-model
defineModel()은 컴포넌트 양방향 바인딩을 위한 현대(Vue 3.4+) 매크로로 부모의 v-model과 자동 동기화되는 ref를 반환합니다. 여러 바인딩에는 이름 있는 모델 v-model:fieldName을 사용하세요. 내부적으로 'update:modelValue'(또는 'update:fieldName')를 emit하고 부모가 바인딩된 ref를 동기화합니다. 구버전 코드는 defineProps + defineEmits를 수동 사용합니다.
<!-- CustomInput.vue -->
<script setup>
const model = defineModel()
</script>
<template>
<input :value="model" @input="model = $event.target.value" />
</template>
<!-- Parent.vue -->
<template>
<CustomInput v-model="text" />
</template>
<!-- multiple v-models (Vue 3.4+) -->
<template>
<UserForm v-model:name="name" v-model:email="email" />
</template>폼 바인딩
텍스트와 Textarea
텍스트 입력의 v-model은 매 input 이벤트에서 동기화합니다. textarea에는 v-model을 요소에 직접 두세요(:value로 하면 안 됨, 속성의 여러 줄 내용은 동작하지 않음). 수정자: .lazy(blur/change에서 동기화, 갱신 적음), .trim(공백 제거), .number(값을 Number로 캐스트). 수정자를 연결할 수 있습니다: v-model.lazy.trim.
<script setup>
import { ref } from 'vue'
const text = ref('')
const message = ref('')
</script>
<template>
<!-- text input: binds on every keystroke -->
<input v-model="text" placeholder="Type here" />
<p>You typed: {{ text }}</p>
<!-- textarea: insert tags inside, not :value -->
<textarea v-model="message" rows="4"></textarea>
<p>Preview: {{ message }}</p>
<!-- .lazy: sync on 'change' (blur) instead of 'input' -->
<input v-model.lazy="text" />
<!-- .trim: strip leading/trailing whitespace -->
<input v-model.trim="text" />
<!-- .number: cast to Number (NaN if invalid) -->
<input v-model.number="age" type="number" />
</template>체크박스와 라디오
체크박스 하나는 불리언에 바인딩됩니다(checked = true). 같은 v-model을 공유하는 여러 체크박스는 value 속성의 배열에 바인딩되며 선택하면 값이 추가되고 해제하면 제거됩니다. v-model을 공유하는 라디오 버튼은 선택된 옵션 값을 ref에 바인딩합니다. true-value / false-value 속성으로 불리언 매핑을 사용자 정의하세요.
<script setup>
import { ref } from 'vue'
const agreed = ref(false)
const fruits = ref([]) // array for multi-checkbox
const picked = ref('') // string for radio
</script>
<template>
<!-- single checkbox -> boolean -->
<input type="checkbox" v-model="agreed" /> I agree
<!-- multiple checkboxes with same v-model -> array -->
<input type="checkbox" value="apple" v-model="fruits" /> Apple
<input type="checkbox" value="banana" v-model="fruits" /> Banana
<input type="checkbox" value="cherry" v-model="fruits" /> Cherry
<p>Selected: {{ fruits }}</p>
<!-- radio: value binds to the chosen option -->
<input type="radio" value="A" v-model="picked" /> A
<input type="radio" value="B" v-model="picked" /> B
</template>Select
<select>에서 v-model은 option이 아니라 select 요소에 두고 선택된 option 값과 동기화합니다. '선택하세요' UX에는 빈 값을 가진 비활성 자리 표시자 option을 사용하세요. 동적 option은 v-for로 렌더링하고 :value를 바인딩하세요. 다중 선택에는 multiple 속성을 추가하면 v-model이 선택된 값 배열에 바인딩됩니다.
<script setup>
import { ref } from 'vue'
const selected = ref('')
const multi = ref([])
const options = [
{ value: 'a', label: 'Option A' },
{ value: 'b', label: 'Option B' }
]
</script>
<template>
<!-- single select -->
<select v-model="selected">
<option disabled value="">Please select</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
<!-- dynamic options -->
<select v-model="selected">
<option v-for="opt in options" :key="opt.value" :value="opt.value">
{{ opt.label }}
</option>
</select>
<!-- multi-select (hold Ctrl/Cmd) -> array -->
<select v-model="multi" multiple>
<option value="x">X</option>
<option value="y">Y</option>
</select>
</template>폼 제출과 검증
@submit.prevent로 기본 페이지 새로고침을 막으면서 폼 제출을 처리하세요. 반응형 폼 객체는 관련 필드를 묶습니다. 복잡한 폼에는 VeeValidate나 Zod + 컴포저블 같은 라이브러리가 인기지만, errors 객체를 반환하는 간단한 validate() 함수도 작은 폼에 잘 맞습니다. SPA 스타일 제출을 위해 항상 기본 동작을 막으세요.
<script setup>
import { reactive, ref } from 'vue'
const form = reactive({
email: '',
password: ''
})
const errors = ref({})
function validate() {
errors.value = {}
if (!form.email.includes('@')) errors.value.email = 'Invalid email'
if (form.password.length < 6) errors.value.password = 'Too short'
return Object.keys(errors.value).length === 0
}
function onSubmit() {
if (!validate()) return
// submit form...
}
</script>
<template>
<form @submit.prevent="onSubmit">
<input v-model.trim="form.email" />
<span v-if="errors.email">{{ errors.email }}</span>
<input type="password" v-model="form.password" />
<span v-if="errors.password">{{ errors.password }}</span>
<button type="submit">Submit</button>
</form>
</template>커스텀 컴포넌트와 v-model
재사용을 위해 폼 필드를 커스텀 컴포넌트로 감싸세요. defineModel()은 부모 값을 읽고 'update:modelValue' emit으로 되쓰는 ref를 반환합니다. 컴포넌트는 :value를 모델에 바인딩하고 @input으로 갱신합니다. 이 패턴으로 네이티브 요소처럼 v-model로 쓸 수 있는 일관된 폼 입력 디자인 시스템(BaseInput, BaseSelect, BaseCheckbox)을 만들 수 있습니다.
<!-- BaseInput.vue -->
<script setup>
const model = defineModel()
defineProps({
label: String,
type: { type: String, default: 'text' }
})
</script>
<template>
<label>
{{ label }}
<input
:type="type"
:value="model"
@input="model = $event.target.value"
/>
</label>
</template>
<!-- Usage -->
<template>
<BaseInput v-model="email" label="Email" type="email" />
</template>컴포넌트
컴포넌트 정의와 사용
컴포넌트는 템플릿, 스크립트, 선택적 스타일을 가진 .vue 파일입니다. 가져오면 <script setup>에서 로컬 자동 등록되고 커스텀 HTML 태그로 사용합니다. 컴포넌트 이름은 스크립트에서 PascalCase이고 템플릿에서는 kebab-case(my-button)일 수 있으며 Vue가 정규화합니다. 전역 등록 컴포넌트(app.component)는 가져오기 없이 어디서나 사용 가능합니다.
<!-- MyButton.vue -->
<template>
<button class="btn"><slot /></button>
</template>
<!-- App.vue -->
<script setup>
import MyButton from './MyButton.vue'
</script>
<template>
<MyButton>Click me</MyButton>
</template>동적 컴포넌트
<component :is='...'>는 컴포넌트를 동적으로 렌더링합니다. 값은 등록된 이름 문자열, 가져온 컴포넌트 객체, defineAsyncComponent가 될 수 있습니다. 탭을 전환할 때 컴포넌트 상태(폼 입력, 스크롤 위치)를 보존하려면 <keep-alive>로 감싸세요. 컴포넌트 객체에는 깊은 반응성 오버헤드를 피하려고 ref가 아닌 shallowRef를 사용하세요.
<script setup>
import { ref, shallowRef } from 'vue'
import HomeTab from './HomeTab.vue'
import PostsTab from './PostsTab.vue'
import ArchiveTab from './ArchiveTab.vue'
const tabs = { HomeTab, PostsTab, ArchiveTab }
const current = shallowRef('HomeTab')
// keep component state when switching (e.g. form input)
import { keep-alive } from 'vue' // not real — use the tag
</script>
<template>
<button v-for="(comp, name) in tabs" :key="name" @click="current = name">
{{ name }}
</button>
<keep-alive>
<component :is="tabs[current]" />
</keep-alive>
</template>비동기 컴포넌트
defineAsyncComponent는 첫 렌더 시 컴포넌트를 지연 로드합니다. 청크를 필요할 때 가져와 초기 번들 크기를 줄입니다. 부드러운 UX를 위해 로딩/오류 상태를 설정하세요. 여러 비동기 컴포넌트를 조율하려면 Suspense와 결합하세요. 로더는 컴포넌트 모듈의 Promise를 반환합니다(Vite/Webpack은 동적 import()에 따라 자동 분할).
<script setup>
import { defineAsyncComponent } from 'vue'
// lazy-load on first use (code-split)
const HeavyChart = defineAsyncComponent(() =>
import('./HeavyChart.vue')
)
// with loading, error, delay, timeout states
const AdminPanel = defineAsyncComponent({
loader: () => import('./AdminPanel.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorMsg,
delay: 200, // show loading after 200ms
timeout: 5000 // error if not loaded in 5s
})
</script>
<template>
<HeavyChart />
<AdminPanel />
</template>컴포넌트 v-model(다중)
이름 있는 모델은 한 컴포넌트가 여러 양방향 바인딩을 노출하게 합니다. defineModel('name')이 각각을 선언합니다. 부모는 v-model:name='...'을 씁니다. 여러 필드(예: street, city, zip이 있는 주소 컴포넌트)를 묶는 폼 컴포넌트에 좋습니다. 이름 없는 기본 v-model은 'modelValue'에 매핑됩니다.
<!-- UserForm.vue -->
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>
<template>
<input v-model="firstName" />
<input v-model="lastName" />
</template>
<!-- Parent.vue -->
<template>
<UserForm
v-model:firstName="form.first"
v-model:lastName="form.last"
/>
</template>재귀 및 순환 컴포넌트
컴포넌트는 파일 이름으로 자신을 참조할 수 있습니다(자동 자기 참조). 트리 구조(파일 트리, 댓글 스레드, 메뉴)에 완벽합니다. 두 컴포넌 트 간 순환 참조(A가 B를, B가 A를 가져옴)에는 하나를 defineAsyncComponent로 쓰거나 beforeCreate에서 가져오세요. Vue는 재귀 컴포넌트를 처리하지만 무한 루프에 주의하세요. 항상 기저 사례(자식 없음)를 두세요.
<!-- TreeNode.vue -->
<script setup>
defineProps({
node: Object
})
// a component can reference itself by its filename
// TreeNode.vue can use <TreeNode /> recursively
</script>
<template>
<div>
{{ node.label }}
<ul v-if="node.children?.length">
<li v-for="child in node.children" :key="child.id">
<TreeNode :node="child" />
</li>
</ul>
</div>
</template>Props
Props 선언
defineProps는 컴포넌트의 입력 계약을 선언합니다. 런타임 선언은 type, default, required, validator를 지원합니다. Vue 3 타입 기반 선언(TS 전용)은 타입 안전성을 주지만 런타임 검증을 잃습니다(volar + 검증 라이브러리와 함께 사용). 객체/배열 기본값은 팩토리 함수를 써야 합니다: default: () => [].
<script setup>
// runtime declaration (validates types)
const props = defineProps({
title: String,
count: { type: Number, default: 0 },
items: { type: Array, required: true },
callback: { type: Function, default: () => {} },
status: {
type: String,
validator: (v) => ['active', 'idle'].includes(v)
}
})
// type-based declaration (TS only, no runtime validation)
const props2 = defineProps<{
title: string
count?: number
}>()
</script>Prop 이름과 전달
Props는 JS에서 camelCase(greetingMessage), 템플릿에서 kebab-case(greeting-message)여야 합니다. HTML은 대소문자를 구분하지 않아 kebab-case가 안전합니다. Vue가 둘 사이를 자동 변환합니다. 정적 문자열 prop은 일반 속성 문법을, 동적 값은 :prop를 사용하세요. 숫자/불리언/객체는 문자열로 취급되지 않도록 항상 :와 함께 넘기세요.
<!-- Child.vue -->
<script setup>
defineProps({
greetingMessage: String,
userId: Number
})
</script>
<!-- Parent.vue -->
<template>
<!-- kebab-case in templates (HTML-friendly) -->
<Child greeting-message="Hello" :user-id="42" />
<!-- camelCase also works in SFC templates -->
<Child greetingMessage="Hello" :userId="42" />
</template>단방향 데이터 흐름
Props는 읽기 전용이며 직접 변경하지 마세요. 개발 모드에서 Vue가 경고합니다. prop 값을 바꾸려면 이벤트를 emit하고 부모가 갱신하게 하세요(단방향 데이터 흐름). 로컬 작업 복사본이 필요하면 prop에서 ref를 초기화하고 watch로 동기화하세요. 가장 깔끔한 양방향 패턴은 emit-and-update 과정을 추상화하는 defineModel의 v-model입니다.
<!-- BAD: mutating a prop -->
<script setup>
const props = defineProps(['count'])
function inc() {
props.count++ // WARNING: don't mutate props!
}
</script>
<!-- GOOD: emit to parent, or use local copy -->
<script setup>
import { ref, watch } from 'vue'
const props = defineProps(['count'])
const emit = defineEmits(['update:count'])
// local copy that syncs with prop
const local = ref(props.count)
watch(() => props.count, v => local.value = v)
function inc() {
local.value++
emit('update:count', local.value)
}
</script>Prop 검증과 기본값
Vue는 개발 모드에서 props를 검증하고 실패 시 경고합니다(운영에서는 아님). type은 생성자(String, Number, Boolean, Array, Object, Function, Symbol)나 그 배열을 받습니다. 객체와 배열 기본값은 새 인스턴스를 반환하는 함수여야 합니다. 그렇지 않으면 모든 컴포넌트가 같은 기본 참조를 공유해 변경 버그가 생깁니다. validator는 타입 검사 후 실행됩니다.
<script setup>
const props = defineProps({
// type can be an array of allowed types
value: { type: [String, Number], required: true },
// object/array default MUST be a factory function
list: {
type: Array,
default: () => []
},
// custom validator
age: {
type: Number,
validator: (v) => v >= 0 && v <= 150
},
// multiple checks combined
email: {
type: String,
required: true,
validator: (v) => v.includes('@')
}
})
</script>불리언 캐스팅과 속성 폴스루
불리언 prop은 특별 캐스팅이 있습니다. 값 없이 존재하면 true입니다. 속성 폴스루는 prop이 아닌 속성(class, style, id, data-*)을 루트 요소로 자동 전달합니다. 루트가 여러 개면 원하는 요소에 v-bind='$attrs'를 명시해야 합니다. 완전한 제어를 원하면 defineOptions({ inheritAttrs: false })로 폴스루를 끄세요.
<!-- prop declared as Boolean -->
<script setup>
defineProps({
disabled: Boolean,
active: Boolean
})
</script>
<!-- Parent -->
<template>
<MyButton disabled /> <!-- disabled = true -->
<MyButton :disabled="false" /> <!-- disabled = false -->
<MyButton /> <!-- disabled = undefined -->
</template>
<!-- Attribute fallthrough: non-prop attributes
land on the root element automatically -->
<template>
<!-- <MyButton data-id="5" class="large" /> -->
<!-- the data-id and class merge onto the <button> root -->
<button>...</button>
</template>Emits
선언과 emit
defineEmits는 컴포넌트가 emit할 수 있는 이벤트를 선언합니다. 객체 형식은 페이로드를 받아 false를 반환하면 경고하는 validator를 허용합니다(개발 모드). emit은 트리 위로 올라가며 부모가 @event-name으로 듣습니다. 항상 emits를 명시 선언하세요. API를 문서화하고 속성 폴스루 제외를 가능하게 하며 검증을 지원합니다. emit()은 이벤트 이름과 선택적 페이로드 인자를 받습니다.
<script setup>
// declare emits (with optional validation)
const emit = defineEmits({
// null-ish = no validation
click: null,
// function = validate payload
submit: (payload) => {
if (!payload.email) {
console.warn('submit needs email')
return false
}
return true
}
})
function handleSubmit() {
emit('submit', { email: '[email protected]', name: 'Alice' })
}
</script>emit 듣기
부모는 @event-name(또는 v-on:event-name)으로 듣습니다. 핸들러는 emit된 페이로드를 받습니다. 인라인 화살표 함수는 간단한 변환에 편리합니다(@increment='n => count += n'). 메서드 핸들러는 첫 인자로 페이로드를 자동으로 받습니다. 컴포넌트 루트 요소의 네이티브 DOM 이벤트는 emits에 선언되지 않으면 폴스루됩니다. 'click'을 선언하면 커스텀 이벤트가 됩니다.
<!-- Child.vue -->
<script setup>
const emit = defineEmits(['increment', 'delete'])
function click() {
emit('increment', 5)
}
</script>
<template>
<button @click="click">+5</button>
</template>
<!-- Parent.vue -->
<template>
<!-- inline handler -->
<Child @increment="n => count += n" />
<!-- method handler -->
<Child @increment="onIncrement" @delete="onDelete" />
</template>
<script setup>
function onIncrement(amount) {
console.log('incremented by', amount)
}
</script>v-model 구현
컴포넌트의 v-model은 :modelValue + @update:modelValue의 편의 문법입니다. 자식은 modelValue prop으로 값을 받고 update:modelValue를 emit해 동기화합니다. 수동 패턴이며 defineModel()(Vue 3.4+)이 이를 감쌉니다. 이름 있는 v-model(v-model:foo)에는 prop 이름 foo와 이벤트 update:foo를 씁니다. 네이티브 입력처럼 동작하는 폼 컴포넌트를 만들 수 있습니다.
<!-- CustomInput.vue (manual implementation) -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
function onInput(e) {
emit('update:modelValue', e.target.value)
}
</script>
<template>
<input
:value="modelValue"
@input="onInput"
/>
</template>
<!-- Parent -->
<template>
<CustomInput v-model="text" />
</template>emit 검증
emit validator는 페이로드 인자를 받고 false를 반환하면 개발 모드 경고를 트리거합니다. emit을 막지는 않고 경고만 합니다. 개발 초기에 계약 위반을 잡습니다. 예상 페이로드 모양을 문서화하는 데 사용하세요. 운영에서는 validator가 제거되므로 보안이나 제어 흐름에 의존하지 마세요.
<script setup>
const emit = defineEmits({
// no validation
click: null,
// validate payload; return false to warn
change: (value) => {
if (typeof value !== 'string') {
console.warn('change payload must be string')
return false
}
return true
},
// validate multiple args
update: (id, value) => {
if (!id || value === undefined) return false
return true
}
})
// validation runs on emit
emit('change', 123) // warns: must be string
</script>이벤트 vs Props: 언제 쓸까
단방향 데이터 흐름을 따르세요: props는 아래로, 이벤트는 위로. 양방향 바인딩에는 v-model(props + emit 편의 문법)을 사용하세요. 깊게 중첩된 통신에서는 prop 드릴링이 고통스러우므로 의존성 주입에는 provide/inject를, 공유 상태에는 스토어(Pinia)를 사용하세요. 이벤트는 '무언가 일어났음' 알림이고 props는 '여기 데이터'입니다.
<!-- Parent-to-child: props (down) -->
<template>
<Child :data="parentData" :config="config" />
</template>
<!-- Child-to-parent: emits (up) -->
<template>
<Child @change="onChange" @submit="onSubmit" />
</template>
<!-- Two-way: v-model (combines both) -->
<template>
<Child v-model="value" />
</template>
<!-- For complex state, prefer provide/inject or a store -->슬롯
기본 슬롯
슬롯은 부모가 자식 컴포넌트 템플릿에 콘텐츠를 주입하게 합니다. <slot> 요소가 자리 표시자입니다. 부모의 자식 콘텐츠가 기본 슬롯을 채웁니다. 슬롯은 합성을 가능하게 합니다. Card는 래퍼 스타일을 처리하고 부모는 내부 콘텐츠를 제어합니다. 슬롯이 없으면 가능한 모든 내부 요소마다 prop이 필요하지만 슬롯이 훨씬 유연합니다.
<!-- Card.vue -->
<template>
<div class="card">
<slot />
</div>
</template>
<!-- Usage -->
<template>
<Card>
<p>This goes into the default slot</p>
<button>Action</button>
</Card>
</template>이름 있는 슬롯
이름 있는 슬롯은 컴포넌트가 여러 콘텐츠 자리 표시자를 갖게 합니다. <slot name='foo' />로 선언하고 <template #foo>로 채웁니다. #는 v-slot:의 단축입니다. 이름 없는 슬롯은 'default' 슬롯이며 template 래퍼가 없는 콘텐츠가 그곳으로 갑니다. 레이아웃(header, sidebar, main, footer)에서 부모가 각 영역을 채울 때 완벽합니다.
<!-- Layout.vue -->
<template>
<header><slot name="header" /></header>
<main><slot /></main>
<footer><slot name="footer" /></footer>
</template>
<!-- Usage with # shorthand -->
<template>
<Layout>
<template #header>
<h1>My Page Title</h1>
</template>
<!-- default slot (no #name) -->
<p>Main content here</p>
<template #footer>
<p>© 2025</p>
</template>
</Layout>
</template>슬롯 Props(범위 슬롯)
범위 슬롯은 자식이 부모의 슬롯 콘텐츠로 데이터를 다시 전달하게 합니다. 자식은 <slot :item='item'>에 데이터를 바인딩하고 부모는 v-slot='{ item }'(또는 #default='{ item }')으로 받습니다. 재사용 목록 컴포넌트(데이터 표, 가상 목록)의 기반입니다. 자식이 반복을 처리하고 부모가 각 항목 렌더링을 제어합니다.
<!-- List.vue -->
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot :item="item" :index="index" />
</li>
</ul>
</template>
<script setup>
defineProps(['items'])
</script>
<!-- Usage: receive slot props via v-slot -->
<template>
<List :items="todos">
<template #default="{ item, index }">
<input type="checkbox" v-model="item.done" />
<span :class="{ done: item.done }">{{ index }}: {{ item.text }}</span>
</template>
</List>
</template>기본 슬롯 콘텐츠
슬롯 폴백 콘텐츠는 <slot>과 </slot> 사이에 둡니다. 부모가 슬롯 콘텐츠를 제공하지 않을 때만 렌더링됩니다. 버튼 라벨, 빈 상태 메시지, 자리 표시자 같은 합리적인 기본값에 좋습니다. 부모가 빈 문자열이라도 넘기면 폴백이 덮어써집니다.
<!-- Button.vue -->
<template>
<button>
<slot>Click here</slot> <!-- fallback content -->
</button>
</template>
<!-- Usage -->
<template>
<Button /> <!-- renders "Click here" -->
<Button>Save</Button> <!-- renders "Save" -->
</template>렌더 범위와 슬롯 사용
슬롯 콘텐츠는 부모 범위에서 렌더링됩니다. 부모 상태에 접근할 수 있지만 슬롯 props 없이는 자식 상태에 직접 접근할 수 없습니다. 이 분리로 자식은 메커니즘(페이지네이션, 가상화, 가져오기)을, 부모는 표현을 처리합니다. 범위 슬롯 패턴(FancyList + UserCard)은 강력한 합성 기법으로 자식이 데이터 흐름을, 부모가 렌더링을 소유합니다.
<!-- FancyList.vue (scoped slot pattern) -->
<script setup>
const props = defineProps(['items', 'pageSize'])
import { ref, computed } from 'vue'
const page = ref(1)
const paged = computed(() =>
props.items.slice((page.value - 1) * props.pageSize, page.value * props.pageSize)
)
</script>
<template>
<div v-for="item in paged" :key="item.id">
<slot :item="item" :page="page" />
</div>
</template>
<!-- Usage: parent fully controls rendering -->
<FancyList :items="users" :pageSize="10">
<template #default="{ item, page }">
<UserCard :user="item" />
<small>Page {{ page }}</small>
</template>
</FancyList>수명 주기 훅
Composition API 훅
수명 주기 훅은 특정 단계에서 실행됩니다. onMounted는 DOM 렌더 후 실행됩니다(요소 접근, 캔버스 라이브러리 실행, 데이터 가져오기에 안전). onUpdated는 모든 반응형 갱신 후 실행되므로 여기서 상태를 변경하지 마세요(무한 루프). onUnmounted는 정리(타이머, 리스너, 구독)용입니다. 훅은 setup에서 동기 호출해야 하지만 여러 번 호출할 수 있습니다.
<script setup>
import {
onBeforeMount, onMounted,
onBeforeUpdate, onUpdated,
onBeforeUnmount, onUnmounted,
onActivated, onDeactivated,
onErrorCaptured
} from 'vue'
onBeforeMount(() => console.log('before mount'))
onMounted(() => console.log('mounted — DOM ready'))
onBeforeUpdate(() => console.log('before re-render'))
onUpdated(() => console.log('after re-render'))
onBeforeUnmount(() => console.log('before unmount'))
onUnmounted(() => console.log('unmounted — cleanup'))
</script>Setup vs Created
<script setup>에서 스크립트 본문 전체가 컴포넌트 초기화 중 실행되며 Options API의 beforeCreate + created와 같습니다. 별도 created() 훅은 없습니다. 최상위 코드(선언, 함수 호출, 비동기 작업까지)는 인스턴스당 한 번 실행됩니다. 데이터 가져오기를 시작하는 흔한 위치입니다(onMounted도 괜찮고 fetch 시작은 동일).
<script setup>
// <script setup> runs BEFORE the component is mounted
// (equivalent to beforeCreate + created in Options API)
import { ref } from 'vue'
// this code runs once per component instance,
// before reactive state is exposed to the template
const count = ref(0)
console.log('component created, count =', count.value)
// no need for created() hook — just run code here
fetch('/api/data')
.then(r => r.json())
.then(data => { /* ... */ })
</script>Mounted와 정리
설정/정리 쌍이 필수입니다. onMounted에서 추가한 모든 리스너, 타이머, 구독, 옵저버는 onUnmounted에서 반드시 제거해야 합니다. 정리를 놓치면 메모리 누수와 파괴된 컴포넌트에서 발생하는 좀비 핸들러가 생깁니다. 패턴: onMounted에서 addEventListener, onUnmounted에서 removeEventListener. 워처는 반환된 stop 함수를 쓰거나 언마운트 시 자동 정리됩니다.
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const windowWidth = ref(window.innerWidth)
function onResize() {
windowWidth.value = window.innerWidth
}
onMounted(() => {
// setup side effects after DOM is ready
window.addEventListener('resize', onResize)
console.log('mounted')
})
onUnmounted(() => {
// ALWAYS clean up to avoid memory leaks
window.removeEventListener('resize', onResize)
})
</script>KeepAlive 훅
컴포넌트가 <KeepAlive>로 감싸지면 다른 곳으로 전환해도 언마운트되지 않고 비활성화(캐시)됩니다. onActivated와 onDeactivated가 표시/숨김 시 발생합니다. 전체 설정/해체 없이 작업(폴링, 비디오 재생)을 일시 정지/재개하는 데 사용하세요. onMounted는 여전히 한 번(첫 활성화) 발생하고 onUnmounted는 캐시된 동안 절대 발생하지 않습니다. 캐시된 탭의 리소스 사용을 최적화할 수 있습니다.
<script setup>
import { onActivated, onDeactivated } from 'vue'
// these fire when the component is wrapped in <KeepAlive>
// and is being shown (activated) or hidden (deactivated)
onActivated(() => {
console.log('component shown again — resume polling')
startPolling()
})
onDeactivated(() => {
console.log('component hidden but not unmounted — pause')
stopPolling()
})
// onMounted fires only once (first show)
// onActivated fires every time it's re-shown
</script>에러 캡처
onErrorCaptured는 하위 컴포넌트의 오류(템플릿, 렌더, 수명 주기, 워처)를 잡습니다. (error, instance, info)를 받습니다. false를 반환하면 오류가 상위 errorCaptured 핸들러와 전역 errorHandler로 전파되는 것을 막습니다. 자식 오류를 우아하 게 처리하는 경계 컴포넌트(React Error Boundary 같은)에 사용하세요. 비동기 오류 상태에는 Suspense와 결합하세요.
<script setup>
import { onErrorCaptured, ref } from 'vue'
const error = ref(null)
onErrorCaptured((err, instance, info) => {
// err: the error thrown
// instance: component that threw
// info: lifecycle hook or event name where it occurred
error.value = err.message
console.error('Captured:', err, info)
// return false to stop propagation to parent
return false
})
</script>
<template>
<div v-if="error" class="error">{{ error }}</div>
<slot v-else />
</template>Composition API
ref vs reactive
ref()는 모든 값(원시값, 객체)과 동작합니다. JS에서는 .value로 반응형 접근이 필요하지만 템플릿에서는 자동 언랩됩니다. reactive()는 객체/배열에만 동작하며 .value가 필요 없습니다. 원시값과 교체 가능한 값에는 ref를, 그룹화된 상태에는 reactive를 사용하세요. 경험칙: 개별 값에는 ref(), 상태 객체에는 reactive(). 섞어도 되며 reactive 객체 안의 ref는 자동 언랩됩니다.
<script setup>
import { ref, reactive } from 'vue'
// ref: works with any value, access via .value
const count = ref(0)
count.value++
console.log(count.value) // 1
// reactive: only for objects/arrays, no .value needed
const state = reactive({ count: 0, user: { name: 'A' } })
state.count++
console.log(state.count) // 1
// refs auto-unwrap in templates and reactive objects
const wrapper = reactive({ count }) // wrapper.count === count.value
</script>reactive 함정
reactive 객체에는 두 함정이 있습니다. 변수를 재할당할 수 없으므로(state = newObj) 속성을 변경하세요(state.list = []). 구조 분해는 반응성을 잃습니다. 구조 분해된 변수가 스냅샷이기 때문입니다. toRefs()로 reactive 속성을 연결된 ref로 변환하세요. 이런 함정 때문에 많은 개발자가 교체 가능하고(.value 설정) 구조 분해에 친화적인 ref()를 선호합니다.
<script setup>
import { reactive, ref } from 'vue'
const state = reactive({ list: [1, 2, 3] })
// PITFALL 1: replacing the whole object loses reactivity
// state = reactive({ list: [4, 5] }) // ERROR: reassign
// GOOD: mutate properties
state.list = [4, 5]
// PITFALL 2: destructuring loses reactivity
let { list } = state // 'list' is now plain
// list.push(4) won't trigger updates
// FIX: use toRefs to keep reactivity
import { toRefs } from 'vue'
const { list } = toRefs(state) // now list is a ref
</script>toRef와 toRefs
toRef()는 단일 reactive 속성을 연결된 ref로 변환합니다(어느 쪽을 변경해도 다른 쪽에 영향). toRefs()는 모든 속성을 변환하므로 컴포저블에서 reactive 상태를 반환하면서 구조 분해를 보존할 때 유용합니다. toRefs가 없으면 구조 분해된 값이 반응성을 잃습니다. 패턴: 컴포저블이 toRefs(state)를 반환해 소비자가 반응성을 깨지 않고 구조 분해하게 합니다.
<script setup>
import { reactive, toRef, toRefs } from 'vue'
const state = reactive({
count: 0,
name: 'Alice'
})
// toRef: single property -> ref (stays linked to state)
const countRef = toRef(state, 'count')
// toRefs: all properties -> object of refs
const { count, name } = toRefs(state)
countRef.value++ // updates state.count
count.value++ // also updates state.count
console.log(state.count) // 2
</script>Setup의 computed와 watch
<script setup>에서 computed()와 watch()를 가져와 직접 호출합니다. computed는 파생 ref를 만들고 watch는 소스 변경 시 콜백을 실행합니다. watch는 단일 ref, getter, 소스 배열, reactive 객체를 받을 수 있습니다. 핵심 Composition API 기본 요소이며 결합해 로직을 컴포저블로 캡슐화하세요.
<script setup>
import { ref, computed, watch } from 'vue'
const a = ref(1)
const b = ref(2)
// computed: derived value, cached
const sum = computed(() => a.value + b.value)
// watch: side effect on change
watch(sum, (newSum) => {
console.log('sum changed to', newSum)
})
// watch multiple sources
watch([a, b], ([newA, newB]) => {
console.log('a or b changed:', newA, newB)
})
</script>shallowRef와 shallowReactive
shallowRef와 shallowReactive는 깊은 반응성을 포기하고 최상위 참조/속성만 추적합니다. 깊은 추적이 낭비인 큰 데이터 구조(차트 데이터 배열, 3D 장면 그래프 등)의 성능을 크게 개선합니다. 깊은 변경 후 Vue에 수동 알림하려면 triggerRef()를 사용하세요. 성 능 문제를 측정한 뒤에만 사용하세요.
<script setup>
import { shallowRef, shallowReactive, triggerRef } from 'vue'
// shallowRef: only .value changes trigger updates
// (deep changes to .value properties do NOT)
const big = shallowRef({ items: [1, 2, 3] })
big.value.items.push(4) // NO update triggered
big.value = { items: [1,2,3,4] } // update triggered
// force update after deep mutation
big.value.items.push(5)
triggerRef(big) // tells Vue to re-render
// shallowReactive: only root-level props are reactive
const state = shallowReactive({ user: { name: 'A' } })
state.count = 1 // reactive
state.user.name = 'B' // NOT reactive
</script>컴포저블
컴포저블 작성
컴포저블은 재사용 가능한 반응형 로직을 캡슐화하는 함수입니다. 관례상 useSomething으로 이름을 붙입니다. 소비 컴포넌트의 수명 주기에 바인딩되는 Composition API 훅(onMounted 등)을 사용합니다. ref와 메서드를 반환하고 컴포넌트가 구조 분해합니다. 컴포저블은 React 훅의 Vue 대응으로 렌더 props나 HOC 없이 상태 있는 로직을 공유하게 합니다.
<!-- useMousePosition.js -->
import { ref, onMounted, onUnmounted } from 'vue'
export function useMousePosition() {
const x = ref(0)
const y = ref(0)
function update(e) {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
<!-- In component -->
<script setup>
import { useMousePosition } from './useMousePosition'
const { x, y } = useMousePosition()
</script>상태 있는 컴포저블(공유 상태)
상태를 모듈 범위(함수 밖)에 선언하면 싱글턴이 되어 컴포저블을 쓰는 모든 컴포넌트가 같은 상태를 공유합니다. 간단한 전역 상태에는 Pinia의 가벼운 대안입니다. readonly()로 직접 변경 없이 상태를 노출하세요. 컴포넌트는 login/logout을 호출해야 바꿀 수 있습니다. 복잡한 앱에는 더 나은 devtools, 영속성, SSR 지원을 위해 Pinia를 권장합니다.
<!-- useUser.js -->
import { reactive, readonly } from 'vue'
// module-scoped state — shared across all consumers
const state = reactive({
user: null,
loading: false
})
export function useUser() {
async function login(credentials) {
state.loading = true
state.user = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify(credentials)
}).then(r => r.json())
state.loading = false
}
function logout() {
state.user = null
}
return {
user: readonly(state.user), // expose read-only
loading: readonly(state.loading),
login,
logout
}
}useFetch 컴포저블
이 컴포저블은 fetch를 로딩/오류 상태로 감싸고 반응형 url이 바뀌면 다시 가져옵니다. isRef()는 입력이 ref인지 확인하고 unref()는 언랩합니다(ref면 값을, 아니면 그대로 반환). refresh를 반환해 소비자가 수동으로 다시 가져오게 합니다. 이 패턴(반응형 입력 + 자동 재실행 + 상태 노출)은 데이터 가져오기 컴포저블의 기본입니다.
<!-- useFetch.js -->
import { ref, watchEffect, isRef, unref } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
async function doFetch() {
loading.value = true
error.value = null
try {
const res = await fetch(unref(url))
if (!res.ok) throw new Error('HTTP ' + res.status)
data.value = await res.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
}
// re-fetch when url ref changes
if (isRef(url)) {
watchEffect(doFetch)
} else {
doFetch()
}
return { data, error, loading, refresh: doFetch }
}정리가 있는 컴포저블
부수 효과(리스너, 타이머, 구독)를 등록하는 컴포저블은 반드시 정리해야 하며 보통 컴포저블 내부의 onUnmounted로 처리합니다. 이렇게 하면 정리가 컴포저블을 소비하는 컴포넌트에 바인딩되어 소비자가 기억할 필요가 없습니다. 유틸리티 함수보다 컴포저블의 큰 장점이며 컴포넌트 수명 주기에 참여합니다.
<!-- useEventListener.js -->
import { onUnmounted } from 'vue'
export function useEventListener(target, event, callback) {
target.addEventListener(event, callback)
// auto-cleanup when the consuming component unmounts
onUnmounted(() => {
target.removeEventListener(event, callback)
})
}
<!-- Usage -->
<script setup>
import { useEventListener } from './useEventListener'
import { ref } from 'vue'
const key = ref('')
useEventListener(window, 'keydown', (e) => {
key.value = e.key
})
// listener is removed automatically on unmount
</script>컴포저블 관례
관례를 따르세요: (1) use 접두사로 이름 붙이기, (2) ref 반환(일반 값은 반응성을 잃음), (3) 유연성을 위해 ref나 getter를 입력으로 받기, (4) 정리에 onUnmounted 사용, (5) 한 가지 관심사에 집중. 이 관례로 컴포저블끼리 조합 가능하고 사용이 예측 가능해집니다.
<!-- DO: name with 'use' prefix, return refs -->
export function useCounter(initial = 0) {
const count = ref(initial)
const inc = () => count.value++
const dec = () => count.value--
return { count, inc, dec }
}
<!-- AVOID: returning plain values (loses reactivity) -->
export function badCounter() {
let count = 0 // plain variable — NOT reactive!
return { count, inc: () => count++ }
}
<!-- DO: accept refs/getters for flexible inputs -->
export function useSearch(query) {
// query can be a ref, a getter, or a plain value
return watchEffect(() => fetch('/api?q=' + unref(query)))
}반응성 심화
반응형 Proxy 메커니즘
Vue 3 반응성은 Proxy(ES6)를 씁니다. reactive()는 get(의존성 추적)과 set(갱신 트리거)을 가로채는 Proxy를 반환합니다. 원본 객체는 수정되지 않고 감싼 버전을 받습니다. isReactive()는 반응형 프록시인지 확인합니다. 새 속성 추가를 감지하지 못했던 Vue 2의 Object.defineProperty 방식보다 강력합니다.
<script setup>
import { reactive, isReactive, isProxy } from 'vue'
const state = reactive({ count: 0 })
// reactive() wraps the object in a Proxy
// reads/writes are tracked and trigger updates
state.count++ // triggers re-render
// the original object is NOT reactive
const raw = { count: 0 }
const wrapped = reactive(raw)
console.log(raw === wrapped) // false
console.log(isReactive(wrapped)) // true
console.log(isReactive(raw)) // false
console.log(isProxy(wrapped)) // true
</script>ref 언랩 규칙
ref 언랩 규칙: <script>에서는 .value로 접근하고 템플릿과 reactive 객체 안에서는 ref가 .value로 자동 언랩됩니다. 템플릿의 {{ count }}가 .value 없이 동작하는 이유입니다. 자동 언랩은 얕아서 배열/Maps 안의 중첩 ref는 언랩되지 않습니다. ref를 담은 reactive 객체는 할당 시 ref의 값을 변경합니다: state.count = 5는 count.value = 5로 설정됩니다.
<script setup>
import { ref, reactive } from 'vue'
const count = ref(0)
const state = reactive({ count })
// in JS: ref needs .value
count.value = 1
// in reactive object: ref auto-unwraps
console.log(state.count) // 1 (not count.value)
state.count = 5 // updates count.value
// in templates: ref auto-unwraps
// {{ count }} renders count.value
</script>
<template>
<p>{{ count }}</p> <!-- 5, not [object Object] -->
</template>effect와 track/trigger(내부)
effect()는 반응성 뒤의 저수준 기본 요소로 함수를 실행하고 내부의 모든 반응형 읽기를 추적하며 추적된 값이 바뀌면 다시 실행합니다. computed, watch, watchEffect, 컴포넌트 렌더링이 모두 effect 위에 만들어집니다. 앱 코드에서 effect()를 직접 호출하는 일은 드 물고 computed/watch/watchEffect를 선호하지만 엔진입니다. 이해하면 재정렬과 타이밍을 추론하는 데 도움이 됩니다.
<script setup>
import { ref, effect } from 'vue'
const count = ref(0)
// effect runs immediately, then re-runs on dep change
effect(() => {
console.log('count is', count.value)
})
// logs: count is 0
count.value = 10
// logs: count is 10
// internally:
// - effect tracks dependencies accessed inside it
// - setting count.value triggers all tracked effects
</script>markRaw와 readonly
markRaw()는 객체를 반응성에서 영구 제외합니다. 자체 갱신 메커니즘이 있고 Proxy로 감싸면 안 되는 서드파티 클래스 인스턴스(차트, 지도, 게임 상태)에 유용합니다. readonly()는 reactive 객체의 읽기 전용 뷰를 만들어 변경 시 개발 모드에서 경고합니다. 컴포저블/스토어에서 직접 변경을 막으면서 상태를 노출할 때 readonly를 사용하세요.
<script setup>
import { reactive, markRaw, readonly, isReadonly } from 'vue'
// markRaw: opt a value OUT of reactivity forever
const bigChart = markRaw(new HeavyChartLib())
const state = reactive({ chart: bigChart })
// state.chart mutations won't trigger Vue updates
// (use chart's own API to update it)
// readonly: make a reactive object read-only
const original = reactive({ count: 0 })
const frozen = readonly(original)
frozen.count = 5
// warning: target is readonly (dev mode)
console.log(isReadonly(frozen)) // true
</script>커스텀 Ref(팩토리)
customRef()는 의존성 추적과 트리거를 명시적으로 제어하게 합니다. 팩토리는 track()과 trigger()를 받습니다. get()에서 track()을 호출해 의존성을 등록하고 set()에서 trigger()를 호출해 갱신을 알립니다. 디바운스 ref, 지연 ref, 저장소 기반 ref 같은 패턴을 가능하게 합니다. 강력하지만 드물게 사용하세요. 보통 watchEffect + 일반 ref가 더 명확합니다.
<script setup>
import { customRef } from 'vue'
// debounce a ref's updates
function debouncedRef(value, delay = 200) {
let timeout
return customRef((track, trigger) => ({
get() {
track() // tell Vue this value is a dependency
return value
},
set(newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger() // notify Vue of the change
}, delay)
}
}))
}
const text = debouncedRef('', 300)
// input only triggers re-render 300ms after typing stops
</script>Vue Router
라우터 설정
createRouter는 라우팅을 설정합니다. createWebHistory는 HTML5 히스토리 모드(깔끔한 URL, 서버의 index.html 폴백 필요)를 사용합니다. 동적 import()로 라우트 컴포넌트를 지연 로드해 코드 분할하면 각 라우트가 자체 번들이 됩니다. 동적 세그먼트(:id)는 route.params로 접근합니다. app.use(router)로 라우터를 플러그인으로 설치하세요.
<!-- router/index.js -->
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{ path: '/', name: 'home', component: Home },
{
path: '/about',
name: 'about',
// lazy-load for code-splitting
component: () => import('../views/About.vue')
},
{ path: '/user/:id', name: 'user', component: () => import('../views/User.vue') }
]
export const router = createRouter({
history: createWebHistory(),
routes
})
<!-- main.js -->
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'
createApp(App).use(router).mount('#app')RouterView와 RouterLink
<RouterView>는 일치한 라우트 컴포넌트가 렌더링되는 자리 표시자입니다. <RouterLink>는 <a> 태그를 렌더링하지만 클라이언트 측 탐색을 위해 클릭을 가로챕니다(전체 페이지 새로고침 없음). to prop은 문자열 경로나 객체({ name, params, query })를 받습니다. RouterLink는 현재 링크 스타일링을 위해 active/exact-active 클래스를 추가합니다.
<!-- App.vue -->
<template>
<nav>
<!-- RouterLink renders <a>, handles navigation -->
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink :to="{ name: 'user', params: { id: 42 } }">
User 42
</RouterLink>
</nav>
<!-- matched route's component renders here -->
<RouterView />
</template>탐색과 프로그래밍 방식 라우팅
useRouter()는 탐색용 라우터 인스턴스를, useRoute()는 현재 라우트(반응형)를 줍니다. push는 히스토리 항목을 추가(뒤로 가기 동작)하고 replace는 추가하지 않습니다. 라우트 속성(path, params, query, hash, name, matched)은 반응형이라 워처와 computed가 탐색 시 다시 실행됩니다. 앱 내 탐색에는 항상 router.push를 쓰고 SPA를 유지하려면 window.location을 쓰지 마세요.
<script setup>
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// push to a new URL (adds to history)
function goHome() {
router.push('/')
router.push({ name: 'user', params: { id: 1 } })
router.push({ path: '/search', query: { q: 'vue' } })
}
// replace current entry (no back button)
router.replace('/login')
// go back/forward
router.back()
router.forward()
router.go(-2)
// access current route info
console.log(route.path, route.params.id, route.query.q)
</script>라우트 가드
가드는 탐색 흐름을 제어합니다. 전역 beforeEach는 인증 검사에 좋습니다. 라우트별 beforeEnter는 특정 라우트를 가드합니다. 컴포넌트 내 가드(onBeforeRouteLeave, onBeforeRouteUpdate)는 저장하지 않은 변경 경고에 유용합니다. false나 라우트를 반환하면 취소/리다이렉트하고 true/undefined는 확인입니다. 비동기 가드는 Promise를 반환할 수 있습니다. requiresAuth 같은 플래그를 붙이려면 route.meta를 사용하세요.
<!-- router/index.js -->
const router = createRouter({ history, routes })
// global guard: runs on every navigation
router.beforeEach((to, from) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
return '/login' // redirect
}
// return true or undefined to confirm
})
// per-route guard
{ path: '/admin', component: Admin, beforeEnter: (to, from) => {
if (!isAdmin()) return '/403'
}}
// in-component guard
<script setup>
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave((to, from) => {
if (hasUnsavedChanges()) {
return confirm('Discard changes?')
}
})
</script>지연 로딩과 중첩 라우트
중첩 라우트는 부모의 <RouterView> 안에 자식 컴포넌트를 렌더링합니다. 자식은 부모 기준 상대 경로로 정의하세요. 빈 경로('')는 부모 URL과 정확히 일치합니다. 동적 import()는 각 라우트를 자체 번들로 코드 분할합니다. route.meta로 데이터(인증 요구, 제목)를 붙이고 가드에서 to.meta로 접근하세요. 관련 라우트는 청크 이름 주석으로 묶으세요.
const routes = [
{
path: '/dashboard',
component: () => import('../views/Dashboard.vue'),
children: [
{ path: '', component: () => import('../views/Overview.vue') },
{ path: 'stats', component: () => import('../views/Stats.vue') },
{ path: 'settings', component: () => import('../views/Settings.vue') }
]
},
// group routes into one chunk
{
path: '/admin',
component: () => import(/* webpackChunkName: "admin" */ '../views/Admin.vue'),
meta: { requiresAuth: true, role: 'admin' }
}
]상태 관리(Pinia)
스토어 정의
Pinia는 Vue 공식 상태 관리(Vuex 후속)입니다. setup 함수와 defineStore는 Composition API 문법을 줍니다. ref/computed는 state/getter이고 반환된 함수는 action입니다. 첫 인자는 고유 스토어 id입니다. setup 스토어는 유연해 어떤 컴포저블이든 내부에서 쓸 수 있습니다. 더 Vuex스러운 느낌을 원하면 Options 문법(state/getters/actions 객체)을 사용하세요.
<!-- stores/counter.js -->
import { defineStore } from 'pinia'
// setup syntax (composition API style)
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const double = computed(() => count.value * 2)
function increment() {
count.value++
}
function asyncIncrement() {
setTimeout(() => count.value++, 1000)
}
return { count, double, increment, asyncIncrement }
})스토어 사용
setup에서 useStore()를 호출해 스토어에 접근합니다. 반응형 구조 분해에는 storeToRefs()(toRefs 같지만 action은 건너뜀)를 사용하세요. 액션은 스토어에 바인딩되어 있어 직접 구조 분해할 수 있습니다. Pinia는 직접 변경(counter.count = 5)과 $patch를 통한 배치 갱신을 허용합니다. 스토어는 싱글턴이라 모든 컴포넌트에서 같은 인스턴스입니다. app.use(createPinia())로 Pinia를 설치하세요.
<script setup>
import { useCounterStore } from '../stores/counter'
import { storeToRefs } from 'pinia'
const counter = useCounterStore()
// state and getters lose reactivity if destructured directly
// use storeToRefs to preserve it
const { count, double } = storeToRefs(counter)
// actions can be destructured directly (they're functions)
const { increment } = counter
// mutate state directly (Pinia allows it, unlike Vuex)
counter.count = 5
counter.$patch({ count: 10 })
counter.$patch(state => { state.count++ })
</script>
<template>
<p>{{ count }} x 2 = {{ double }}</p>
<button @click="increment">+</button>
</template>Getter와 스토어 합성
Getter는 상태에서 파생된 computed 값입니다. 한 스토어 안에서 다른 스토어를 쓰려면 그 useStore()를 호출하면 Pinia가 의존성을 처리합니다. Vuex 모듈과 달리 스토어 합성이 간단해집니다. Getter는 다른 getter도 참조할 수 있습니다. 비동기 작업은 스토어에 async 함수를 쓰면 되고 Vuex 같은 특별한 'actions' 컨텍스트가 없습니다.
<!-- stores/cart.js -->
import { defineStore } from 'pinia'
import { useUserStore } from './user'
export const useCartStore = defineStore('cart', () => {
const items = ref([])
// getter (computed)
const total = computed(() =>
items.value.reduce((sum, i) => sum + i.price * i.qty, 0)
)
const itemCount = computed(() =>
items.value.reduce((n, i) => n + i.qty, 0)
)
// compose other stores
const userStore = useUserStore()
const canCheckout = computed(() =>
userStore.isLoggedIn && items.value.length > 0
)
function addItem(item) {
items.value.push(item)
}
return { items, total, itemCount, canCheckout, addItem }
})구독과 영속성
$subscribe는 모든 상태 변경(변경 정보와 새 상태 포함)에서 발생합니다. 영속성(localStorage, sessionStorage)이나 외부 시스템 동기화에 사용하세요. $onAction은 액션 호출에 연결되므로 로깅, 분석, 액션 소요 시간 측정에 유용합니다. after/onError 콜백으로 액션 완료나 실패에 반응하세요. 정리는 컴포넌트 언마운트 시 자동입니다.
<script setup>
import { useCartStore } from '../stores/cart'
const cart = useCartStore()
// subscribe to any state change
cart.$subscribe((mutation, state) => {
console.log('cart changed', mutation.type, state)
// persist to localStorage
localStorage.setItem('cart', JSON.stringify(state.items))
})
// subscribe to actions
cart.$onAction(({ name, after, onError }) => {
console.log('action started:', name)
after(result => console.log('action done:', name, result))
onError(err => console.error('action failed:', name, err))
})
</script>리셋과 스토어 모듈
Options 문법 스토어에는 내장 $reset()이 있지만 setup 스토어에는 없으므로 각 ref를 재할당해 reset()을 직접 구현하세요. Pinia는 설계상 모듈식이라 각 스토어가 독립적이고 Vuex 같은 중첩 모듈이 없습니다. 한 스토어 안에서 useOtherStore()를 호출해 스토어를 합성하세요. createPinia()로 Pinia를 전역 설치합니다. 스토어는 트리 셰이킹 가능하고 TypeScript 지원과 devtools 통합이 뛰어납니다.
<!-- stores/user.js -->
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', () => {
const name = ref('')
const isLoggedIn = ref(false)
function login(n) { name.value = n; isLoggedIn.value = true }
function logout() { name.value = ''; isLoggedIn.value = false }
// Pinia setup stores don't have a built-in $reset
// implement it manually
function reset() {
name.value = ''
isLoggedIn.value = false
}
return { name, isLoggedIn, login, logout, reset }
})
<!-- main.js -->
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)전환과 애니메이션
Transition 컴포넌트
v-if/v-show 요소를 <Transition>으로 감싸 enter/leave를 애니메이션하세요. Vue는 적절한 시점에 6개 클래스를 추가합니다: *-enter-from(시작 상태), *-enter-active(전환 중), *-enter-to(끝 상태), 그리고 *-leave-*. 이 클래스에 CSS 전환/애니메이션을 정의하세요. name prop은 'v-' 접두사를 대체합니다. 자식 요소 하나만 허용되며 목록에는 TransitionGroup을 사용하세요.
<template>
<Transition name="fade">
<p v-if="show">Hello</p>
</Transition>
</template>
<style>
/* 6 classes: {name}-enter-{from,active,to}, {name}-leave-{...} */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>전환 모드와 훅
mode='out-in'은 나가는 요소가 완전히 사라진 뒤 들어오는 요소가 시작되어 겹침 없이 컴포넌트(탭)를 교체하기에 완벽합니다. mode='in-out'은 드물게 씁니다. JavaScript 훅(@before-enter, @enter, @leave)으로 GSAP 같은 라이브러리로 애니메이션을 구동하세요. :css='false'는 Vue가 CSS 감지를 건너뛰고 JS 훅만 쓰게 합니다(약간의 성능 이점).
<template>
<!-- 'out-in': current leaves, then new enters -->
<Transition mode="out-in" name="fade">
<component :is="currentTab" />
</Transition>
<!-- JavaScript hooks for GSAP/anime.js -->
<Transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
:css="false"
>
<div v-if="show">Animated</div>
</Transition>
</template>목록용 TransitionGroup
TransitionGroup은 v-for 목록을 세 가지로 애니메이션합니다: enter(새 항목), leave(제거된 항목), move(위치가 바뀌는 기존 항목). *-move 클래스는 FLIP 기법을 애니메이션합니다. Vue가 위치 델타를 계산해 transform 전환을 적용합니다. leave-active에 position: absolute를 설정해 나가는 항목을 흐름에서 빼면 형제가 부드럽게 제자리로 미끄러집니다.
<template>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</TransitionGroup>
</template>
<style>
.list-enter-active, .list-leave-active { transition: all 0.5s; }
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(30px); }
/* the magic class for reordering */
.list-leave-active { position: absolute; }
.list-move { transition: transform 0.5s ease; }
</style><Transition> 래퍼로 상태 애니메이션
enter-active-class와 leave-active-class로 Vue의 기본 클래스 이름을 사용자 정의 클래스로 덮어쓸 수 있습니다. 기존 애니메이션 시스템(Animate.css, Tailwind 애니메이션 유틸리티, 커스텀 키프레임)에 연결할 수 있습니다. 패턴: 클래스에 애니메이션을 정의하고 Vue 전환이 그것을 가리키게 합니다. Vue 수명 주기와 모든 CSS 애니메이션 프레임워크를 잇습니다.
<template>
<button @click="show = !show">Toggle</button>
<Transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut"
>
<div v-if="show" class="box">Content</div>
</Transition>
</template>
<!-- combine with third-party animation libraries -->
<!-- Animate.css, Tailwind animations, custom keyframes -->비동기용 Suspense
Suspense는 async setup을 조율합니다. 자식 컴포넌트가 최상위 await를 쓰면 중단되고 Suspense가 #fallback을 보여줍니다. 모든 비동기 자식이 해결되면 기본 슬롯이 렌더링됩니다. 데이터 가져오기 컴포넌트에 우아합니다. 참고: Suspense는 Vue 3에서 아직 실험적이며 오류 처리는 onErrorCaptured가 필요합니다. 운영에서는 대부분 컴포저블 + 로딩 상태를 사용합니다.
<template>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</template>
<!-- AsyncComponent uses top-level await -->
<script setup>
import { ref } from 'vue'
const data = ref(null)
// top-level await suspends the component
const res = await fetch('/api/data').then(r => r.json())
data.value = res
</script>Teleport와 Suspense
Teleport 기초
Teleport는 콘텐츠를 문서의 다른 DOM 요소(보통 body 수준)로 렌더링하지만 컴포넌트는 부모의 반응형 문맥, props, emits 등을 유지합니다. 부모의 overflow:hidden이나 스태킹 문맥에 잘릴 모달, 툴팁, 드롭다운의 z-index/오버플로 문제를 해결합니다. 'to' 선택자가 목적지 요소를 지정합니다.
<!-- Modal.vue -->
<template>
<!-- the rendered content is moved to #modals in the DOM,
but keeps the component's reactive context -->
<Teleport to="#modals">
<div class="modal">
<h2>{{ title }}</h2>
<slot />
<button @click="$emit('close')">Close</button>
</div>
</Teleport>
</template>
<!-- index.html must have -->
<!-- <div id="app"></div> -->
<!-- <div id="modals"></div> -->조건부 Teleport
disabled prop은 조건부 텔레포트를 가능하게 합니다. true면 콘텐츠가 (텔레포트되지 않고) 제자리에 렌더링됩니다. 같은 컴포넌트를 다른 문맥에서 쓸 때 유용합니다(예: 일반 레이아웃에서는 텔레포트해야 하지만 다른 모달 안에서는 인라인이어야 하는 툴팁). 같은 요소를 대상으로 하는 여러 Teleport는 렌더 순서로 추가됩니다. Teleport는 내부 v-if와 동작합니다.
<template>
<!-- disabled: render in place (not teleported) -->
<Teleport :to="target" :disabled="inline">
<div class="popup" v-if="show">...</div>
</Teleport>
</template>
<script setup>
const props = defineProps({
inline: Boolean // if true, render inline instead of teleporting
})
const target = '#popups'
</script>
<!-- Multiple Teleports to same target: appended in order -->모달과 알림용 Teleport
body로의 Teleport는 모달의 표준 패턴입니다. 모달이 부모의 overflow/transform/z-index 제약을 벗어납니다. enter/leave 애니메이션에는 Transition과 결합하세요. 배경의 @click.self는 바깥(콘텐츠 아님)을 클릭하면 닫습니다. 슬롯으로 부모가 모달의 header, body, footer를 완전히 사용자 정의하고 모달 컴포넌트는 위치와 애니메이션을 처리합니다.
<!-- components/Modal.vue -->
<template>
<Teleport to="body">
<Transition name="modal">
<div v-if="show" class="modal-backdrop" @click.self="$emit('close')">
<div class="modal-content">
<header><slot name="header" /></header>
<slot />
<footer><slot name="footer" /></footer>
</div>
</div>
</Transition>
</Teleport>
</template>Async Setup과 Suspense
자식 컴포넌트의 setup이 최상위 await를 쓰면 Promise를 반환합니다. Suspense가 이를 잡아 해결될 때까지 #fallback을 보여줍니다. 중단된 컴포넌트의 setup 결과는 그 후 렌더링에 사용됩니다. 여러 비동기 자식이 조율되며 Suspense가 모두 기다립니다. onErrorCaptured가 setup 오류를 잡습니다. Suspense는 아직 실험적이므로 운영에서는 컴포저블의 수동 로딩 상태를 권장합니다.
<!-- Parent.vue -->
<template>
<Suspense>
<AsyncProfile :id="userId" />
<template #fallback>
<Spinner />
</template>
</Suspense>
</template>
<!-- AsyncProfile.vue -->
<script setup>
const props = defineProps(['id'])
// top-level await suspends this component
const profile = await fetch(`/api/users/${props.id}`).then(r => r.json())
// component only renders after this resolves
</script>중첩 Suspense와 비동기 컴포넌트
Suspense는 중첩될 수 있고 각 수준이 자체 비동기 경계를 처리합니다. Dashboard(와 필요한 모든 것)가 로드되는 동안 바깥 Suspense는 PageSkeleton을, 안쪽 Suspense는 차트 전용 ChartSkeleton을 보여줍니다. 세밀 한 로딩은 UX를 개선합니다. 페이지 셸이 먼저 나타나고 개별 섹션이 채워집니다. Suspense는 실험적이므로 철저히 테스트하고 onErrorCaptured로 오류를 처리하세요.
<template>
<Suspense>
<template #default>
<Dashboard>
<Suspense>
<template #default>
<AsyncChart :data="data" />
</template>
<template #fallback>
<ChartSkeleton />
</template>
</Suspense>
</Dashboard>
</template>
<template #fallback>
<PageSkeleton />
</template>
</Suspense>
</template>Provide / Inject
기본 Provide와 Inject
provide()는 값을 모든 하위 컴포넌트에서 사용 가능하게 하고 inject()는 트리 아래 어디서나 검색합니다. 깊게 중첩된 컴포넌트의 prop 드릴링을 피합니다. inject의 두 번째 인자는 기본값입니다(제공된 것이 없을 때 사용). 제공된 ref는 반응형이라 하위가 변경하면 부모가 변화를 봅니다. 큰 앱에서는 충돌을 피하려고 Symbol 키를 사용하세요.
<!-- Parent.vue -->
<script setup>
import { provide, ref } from 'vue'
const theme = ref('dark')
const user = ref({ name: 'Alice' })
// provide to all descendants
provide('theme', theme)
provide('user', user)
</script>
<!-- DeepChild.vue (any level of nesting) -->
<script setup>
import { inject } from 'vue'
const theme = inject('theme', 'light') // default 'light'
const user = inject('user')
// these are reactive refs, just like in the parent
</script>읽기 전용 제공 상태
readonly()로 직접 변경 없이 상태를 노출하세요. 하위는 제공된 액션 메서드를 호출해야 바꿀 수 있습니다. 이 패턴(비공개 가변 ref + 읽기 전용 공개 뷰 + 액션 메서드)은 컴포넌트 트리 범위 상태에서 Pinia의 가벼운 대안입니다. 단방향 데이터 흐름을 강제하고 트리 깊 은 곳의 무분별한 변경 버그를 막습니다.
<!-- store.js (shared composable) -->
import { ref, readonly } from 'vue'
const _count = ref(0) // private mutable state
export function useCountStore() {
return {
count: readonly(_count), // consumers can't mutate
increment: () => _count.value++ // only via action
}
}
<!-- Provider.vue -->
<script setup>
import { provide } from 'vue'
import { useCountStore } from './store'
const store = useCountStore()
provide('countStore', store)
</script>타입 지정 주입 키
InjectionKey<Ref<Type>>로 타입 지정 symbol 키를 만드세요. 완전한 TypeScript 추론을 제공해 inject가 반환 타입을 압니다. Symbol 키는 여러 라이브러리가 값을 제공할 때 문자열 충돌을 피합니다. 앱 전역 싱글턴에는 provide/inject보다 Pinia를 권장하세요. Pinia는 devtools, 영속성, 테스트 용이성이 좋습니다. 컴포넌트 트리 범위 문맥(테마, 폼, 로케일)에는 provide/inject를 사용하세요.
<!-- keys.ts -->
import type { InjectionKey, Ref } from 'vue'
import { inject, provide } from 'vue'
export const ThemeKey: InjectionKey<Ref<string>> = Symbol('theme')
<!-- Provider.vue -->
<script setup>
import { ref } from 'vue'
import { ThemeKey } from './keys'
const theme = ref('dark')
provide(ThemeKey, theme)
</script>
<!-- Consumer.vue -->
<script setup>
import { inject } from 'vue'
import { ThemeKey } from './keys'
// TS knows theme is Ref<string> | undefined
const theme = inject(ThemeKey)
// with default
const theme2 = inject(ThemeKey, ref('light'))
</script>제공 값 갱신
권장 패턴: 반응형 상태와 이를 변경하는 메서드를 담은 객체를 제공하세요. API가 명시적이고 무분별한 변경을 막습니다. 자식은 상태와 액션을 구조 분해합니다. 사실상 미니 스토어이므로 값이 몇 개를 넘으면 같은 모양을 반환하는 컴포저블이나 Pinia를 고려하세요. 제공 값은 ref를 담고 있어 반응형입니다.
<!-- Provider.vue -->
<script setup>
import { ref, provide } from 'vue'
const count = ref(0)
// expose value + mutator together
provide('counter', {
count, // reactive ref
increment: () => count.value++,
reset: () => count.value = 0
})
</script>
<!-- DeepChild.vue -->
<script setup>
import { inject } from 'vue'
const { count, increment, reset } = inject('counter')
// count is reactive, increment/reset are actions
</script>
<template>
<p>{{ count }}</p>
<button @click="increment">+</button>
<button @click="reset">Reset</button>
</template>앱 수준 Provide
app.provide()는 앱의 모든 컴포넌트에서 값을 사용 가능하게 하므로 앱 전역 상수(API URL, 기능 플래그, 환경 설정)에 유용합니다. 컴포넌트 수준 provide와 달리 기본적으로 반응형이 아닙니다(ref를 제공하지 않는 한). env 파일을 곳곳에서 가져오지 않고 환경별 설정을 주입하는 좋은 방법입니다. 어떤 컴포넌트에서든 inject()와 결합해 이 전역 값에 접근하세요.
<!-- main.js -->
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// app-level provide — available to ALL components
app.provide('apiUrl', 'https://api.example.com')
app.provide('apiKey', import.meta.env.VITE_API_KEY)
// useful for app-wide constants
app.provide('features', {
darkMode: true,
beta: false
})
app.mount('#app')관련 Vue 3 스니펫
Copy-paste ready code for common tasks.
Single-File Component
Define a Vue 3 component with script setup, template, and scoped styles.
Composition API
Organize reactive state, computed, and lifecycle logic by feature.
Refs & Reactive
Choose between ref and reactive for reactive state.
Computed & Watch
Derive values with computed and react to changes with watch.
Props & Emits
Declare inputs and events, and implement v-model on a component.
Lifecycle Hooks
Register lifecycle callbacks as composable functions.
Slots & Scoped Slots
Distribute content with default, named, and scoped slots.
Composables
Extract reusable reactive logic into a useMouse composable.
Was this helpful?