Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- composition api
- hoisting
- tdz
- async
- 오블완
- watch
- drective
- 티스토리챌린지
- es6
- reactivity
- 템플릿 문법
- html 엔티티
- watchEffect
- Component
- await
- ref
- promise
- const
- synchronus
- vue
- eruda
- let
- mobile dev tools
- dex모드
- computed
- composition API
- setup 함수
- vitre
- 앱 빌드
- asynchronus
Archives
- Today
- Total
uxtry
vue: 템플릿 문법 본문

vue3에서 템플릿 문법은 HTML을 확장한 형태로, 데이터 바인딩 및 디렉티브를 통해 데이터를 UI에 쉽게 연결할 수 있습니다. Vue 템플릿 문법은 기본적으로 HTML과 비슷하지만, Vue가 제공하는 다양한 기능을 활용하여 동적인 사용자 인터페이스를 만들 수 있게 도와줍니다.
1. 데이터 바인딩
- {{ }} (Mustache 구문): 데이터 또는 계산된 값을 HTML에 렌더링 하는데 사용합니다.
<template>
<p>안녕하세요, {{ userNmae }}!</p>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Vue 사용자');
// 결과 -> "안녕하세요, Vue 사용자!"
</script>
- v-bind 디렉티브: 속성에 데이터를 바인딩할 때 사용합니다.
<template>
<img v-bind:src="imageUrl" alt="Vue 로고"/>
<!--단축형-->
<img :src="imageUrl" alt="Vue 로고"/>
</template>
<script>
const imageUrl ="https://vuejs.org/images/logo.png";
</script>
2. 디렉티브(Drectives)
Vue의 디렉티브는 HTML속성을 확장하여 템플릿을 더 동적으로 만들어 줍니다.
- v-if: 조건에 따라 요소를 렌더링합니다.
<template>
<p v-if="isLoggedIn">로그인 되었습니다.</p>
<p v-else>로그인이 필요합니다.</p>
</template>
<script setup>
imnport { ref } from "vue";
const isLoggedIN = ref(false); // false로 "로그인이 필요합니다."
</script>
- v-show: 조건에 따라 요소의 표시여부를 제어합니다. v-if와 달리 DOM에는 항상 렌더링되며ㅡ display:none;으로 숨깁니다.
<template>
<p v-show="isVisible">이 문장은 보입니다.</p>
</template>
<script setup>
import { ref } from 'vue';
const isVisible = ref(true); //show가 true속성으로 보임
</script>
- v-for: 리스트를 렌더링할 때 사용합니다. 각 항목에 고유한 key를 설정하여 Vue가 효율적으로 업데이트할 수 있게 합니다.
<template>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}></li>
</ul>
</template>
<scripe setup>
const items = ["사과", "바나나", "체리"];
</script>
★ Vue SFC Playground 코드 실행 →
3.이벤트 핸들링
- v-on 디렉티브: 이벤트 리스터를 추가합니다. @를 통해 단축형을 사용할 수 있습니다.
<template>
<button v-on:click="increment">클릭하세요</button>
<!-- 단축형: -->
<buttonm @click="increment">클릭하세요</button>
<p>클릭 회수: {{ count }}</p>
</template>
<script setup>
import { ref } from 'vue';
cpnst count = ref(0);
const increment = () => {
count.value ++;
}
</script>
★ Vue SFC Playground 코드 실행 →
- 이벤트 수식어: .stop, .prevent, .capture 등 수식어를 통해 이벤트 동작을 제어할 수 있습니다.
<button @click.stop="doSomething">이벤트 전파 멈춤</button>
<button @submit.prevent="onSubmit">기본 동작 방지</button>
4.양방향 데이터 바인딩
- v-model: 양방향 데이터 바인딩을 위해 사용합니다. 주로 폼요소에 사용됩니다.
<template>
<input v-model="message" placeholder="메시지를 입력하세요">
<p>입력한 메시지: {{ message }}</p>
</template>
<script setup>
import { ref } from 'vue';
const message = ref("");
</script>
★ Vue SFC Playground 코드 실행 →
- v-model 수식어: .lazy, .number, .trim 등 수식어를 추가해 값을 변환하거나 조건을 지정할 수 있습니다.
<input v-model.number="age" placeholder="나이 입력">
5. 계산된 속성(Computed Preperties)
계산된 속성은 데이터에 종속적인 동적인 값이 필요할 때 사용합니다.
<template>
<p>현재 연도: {{ currentYear }}</p>
</template>
<script setup>
import { computed } from 'vue';
const currentYear = conmputed(() => new Date().getFullYear());
//출력 => "현재 연도: 2024"
</script>
6. 클래스와 스타일 바인딩
- 클래스 바인딩: 객체나 배열을 사용해 동적으로 클래스를 추가할 수 있습니다.
<template>
<div :class="{active: isActive}">클래스 바인딩</div>
</template>
<script setup>
import { ref } from 'vue';
cosnt isActive = "ref(true)";
</script>
- 스타일 바인딩: 객체를 사용해 인라인 스타일을 동적으로 적용할 수 있습니다.
<template>
<div :style="{color: textColor, fontSize: fontsize + 'px'}">스타일 바인딩</div>
</template>
<script setup>
const textColor= "blue";
const fontSize = 18;
</script>
★ Vue SFC Playground 코드 실행 →
7. 조건부 렌더링(v-if, v-else-if, v-else)
조건에 따라 특정 요소를 보여주거나 숨길 수 있습니다.
<template>
<p v-if="status === 'success'">성공했습니다!</p>
<p v-else-if="status === 'pending'">처리 중입니다...</p>
<p v-else>오류가 발생했습니다.</p>
</template>
<script setup>
import { ref } from 'vue';
const status = ref("success");
//결과 => 성공했습니다!
</script>
8. 슬롯 (Slot)
슬롯을 사용하여 컴포넌트에 콘텐츠를 전달할 수 있습니다.
<!-- ParentComnponent.vue -->
<template>
<ChildComponent>
<template v-slot:header>헤더 콘텐츠</template>
본문 콘텐츠
</ChildComponent>
</template>
<!--ChildComponent.vue-->
<template>
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<template>
요약
Vue3 템플릿 문법은 기본 HTML에 Vue만의 기능을 추가하여, 데이터 바인딩, 조건부 렌더링, 이벤트 처리 등을 쉽게 구현할 수 있게 도와줍니다. 이 문법을 잘 활용하면 동적인 UI를 간결하게 구성할 수 있습니다.
'Vue.js 3 주요 문법 (vue:)' 카테고리의 다른 글
| vue: Computed (0) | 2024.11.13 |
|---|---|
| vue: 반응형 기초(reactivity) (0) | 2024.11.12 |
| vue: setup 함수 (0) | 2024.11.08 |
| vue: Composition API 간략설명 (0) | 2024.11.08 |
| vue: Vue 3 새롭게 달라진 점 (0) | 2024.10.30 |