| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 31 |
Tags
- reactivity
- Dictionary
- emit
- map
- graceful shutdown
- CDN
- goroutines
- container
- localStorage
- Matrix
- Vue.js
- channel
- Refactoring
- toggle
- PROPS
- TODO
- golang
- Vue
- SFC
- websocket
- Server
- URL
- todo-list
- App.vue
- component
- cli
- method
- go
- 행렬
- goroutine
Archives
- Today
- Total
ksundev 님의 블로그
Vue 데이터 바인딩: id, class, style 본문
Vue.js 클래스와 스타일 바인딩
Vue.js에서 동적으로 CSS 클래스와 스타일을 바인딩하는 방법에 대해 알아보겠습니다. Vue.js는 v-bind 디렉티브를 사용하여 HTML 속성을 동적으로 바인딩할 수 있으며, 특히 클래스와 스타일 바인딩에서 자주 사용됩니다.
v-bind 디렉티브의 축약형
Vue.js에서 v-bind는 매우 자주 사용되는 디렉티브이기 때문에 축약형 :을 제공합니다.
이번 포스트 이후로부터는 축약형:형태로 쓸 계획이니 참고하시기 바랍니다.
<!-- 전체 형태 -->
<div v-bind:class="textClass">안녕하세요.</div>
<!-- 축약형 -->
<div :class="textClass">안녕하세요.</div>
구현 예제
<style>
.primary {
color: chocolate;
}
</style>
<!-- HTML -->
<div id="app">
<!-- class 바인딩 -->
<h1>클래스 바인딩</h1>
<div :class="textClass">안녕하세요.</div>
<!-- id 바인딩 -->
<h1>아이디 바인딩</h1>
<section :id="tab1" :style="sectionStyle">반갑습니다.</section>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
Vue.createApp({
data() {
return {
textClass: "primary",
sectionId: "tab1",
sectionStyle: { color: "red" },
};
},
}).mount("#app");
</script>
클래스 바인딩
기본 클래스 바인딩
<div :class="textClass">안녕하세요.</div>
textClass데이터 속성의 값이 동적으로 클래스로 적용됩니다.- 위 예제에서는
textClass가"primary"이므로<div class="primary">가 됩니다.
객체 형태의 클래스 바인딩
<div :class="{ primary: isPrimary, active: isActive }">동적 클래스</div>
data() {
return {
isPrimary: true,
isActive: false
}
}
배열 형태의 클래스 바인딩
<div :class="[baseClass, conditionalClass]">배열 클래스</div>
data() {
return {
baseClass: 'base',
conditionalClass: 'conditional'
}
}
스타일 바인딩
객체 형태의 스타일 바인딩
<section :style="sectionStyle">반갑습니다.</section>
data() {
return {
sectionStyle: {
color: "red",
fontSize: "20px",
fontWeight: "bold"
}
}
}
인라인 스타일 바인딩
<div :style="{ backgroundColor: bgColor, color: textColor }">인라인 스타일</div>
data() {
return {
bgColor: 'blue',
textColor: 'white'
}
}
ID 바인딩
<section :id="sectionId">반갑습니다.</section>
sectionId데이터 속성의 값이 동적으로 id 속성으로 적용됩니다.- 위 예제에서는
sectionId가"tab1"이므로<section id="tab1">이 됩니다.
v-bind 축약형의 장점
- 간결성:
v-bind:대신:만 사용하여 코드가 더 간결해집니다. - 가독성: 자주 사용되는 디렉티브이므로 축약형이 더 읽기 쉽습니다.
- 일관성: Vue.js 커뮤니티에서 표준으로 사용되는 방식입니다.
실무 활용 예제
조건부 클래스 적용
<button :class="{
'btn-primary': isPrimary,
'btn-secondary': !isPrimary,
'btn-disabled': isDisabled
}">
버튼
</button>
동적 스타일 적용
```html
'[개발] Vue.js > 기본' 카테고리의 다른 글
| [SFC] App.vue 파일 구조 (0) | 2025.06.24 |
|---|---|
| [Vue] CDN에서 CLI로 넘어가기 (1) | 2025.06.23 |
| Vue 디렉티브 - (v-if, v-show) (0) | 2025.06.21 |
| Vue의 Component 통신 방식 - 3. 같은 level 끼리 (2) | 2025.06.21 |
| Vue의 Component 통신 방식 - 2. Event Emit (0) | 2025.06.19 |