Vue의 SFC(Single File Component)는 Vue의 독자적인 구성 방식으로, HTML, JavaScript, CSS를 한 파일 안에서 작성하는 시스템입니다.
<template>
<!-- Vue 컴포넌트의 HTML 구조 -->
<div class="app">
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
title: "Vue SFC 기본 구조",
};
},
};
</script>
<style>
/* Vue 컴포넌트의 스타일 */
.app {
text-align: center;
color: #42b983;
}
</style>
옵션 API는 data, methods, computed, watch, props, components, emits 등 다양한 옵션을 통해 컴포넌트를 구성하는 방식입니다.
옵션 API의 핵심은 컴포넌트의 설정을 객체 형식으로 정의하는 것입니다.
이 방식은 코드가 명확하고 이해하기 쉽지만, 상태 관리가 복잡해지면 코드가 다소 길어질 수 있습니다.
그러나 Vue 3에서 제공하는 Composition API와 비교할 때, 옵션 API는 더 직관적이고 학습 곡선이 낮습니다.
data 속성은 컴포넌트의 상태를 정의하는 객체입니다. 이 객체의 프로퍼티는 컴포넌트에서 사용할 수 있는 데이터가 됩니다.
const app = Vue.createApp({
data() {
return {
message: 'Hello, Vue!',
count: 0
};
}
});
데이터 보간은 템플릿에서 데이터를 표시하는 방법입니다. 중괄호({{ }})를 사용하여 데이터를 출력할 수 있습니다.
<div id="app">
<h1>{{ message }}</h1>
<p>Count: {{ count }}</p>
<button @click="count++">Increase Count</button>
</div>
HTML, 텍스트를 안전하게 출력합니다.
data() {
return {
htmlContent: '<strong>This is bold text</strong>'
rawText: '<h1>This will not be rendered</h1>'
};
}
<div v-html="htmlContent"></div>
<div v-text="message"></div>
내용을 출력하기 전에 컴파일하지 않도록 합니다.
data() {
return {
rawText: '<h1>This will not be rendered</h1>'
};
}
<pre v-pre>{{ rawText }}</pre>
HTML 속성에 데이터를 바인딩합니다.
data() {
return {
imageSrc: 'path/to/image.jpg'
};
}
<img v-bind:src="imageSrc" alt="Dynamic Image">
<--축약 가능-->
<img :src="imageSrc" alt="Dynamic Image">
<-- 속성과 변수 이름이 같을 경우 -->
<img :src alt="Dynamic Image">
조건에 따라 요소를 렌더링합니다.
<div v-if="count > 0">Count is positive</div>
<div v-else-if="count < 0">Count is negative</div>
<div v-else>Count is zero</div>
조건에 따라 요소의 표시 여부를 결정합니다. (CSS display 속성 사용)
data() {
return {
isVisible: true
};
}
<div v-show="isVisible">This is visible</div>
Vue가 컴파일될 때까지 해당 요소를 숨깁니다.
<div v-cloak>{{ message }}</div>
<style>
[v-cloak] { display: none; }
</style>
리스트를 반복하여 렌더링합니다.
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>