1️⃣ HTML의 스타일 속성 바인딩
2️⃣ CSS 클래스 바인딩
3️⃣ 동적 스타일 바인딩
=> 스타일을 동적으로 변경하거나 조건에 맞게 바인딩할 수 있다 !
:style):style 디렉티브를 사용하여 인라인 스타일을 동적으로 바인딩:style은 객체 또는 배열 형식으로 스타일을 지정<div id="app">
<p :style="{ color: textColor, fontSize: fontSize + 'px' }">스타일 바인딩 예제</p>
<button @click="changeStyle">스타일 변경</button>
</div>
<script>
Vue.createApp({
data() {
return {
textColor: 'blue',
fontSize: 20,
};
},
methods: {
changeStyle() {
this.textColor = 'red';
this.fontSize = 30;
},
},
}).mount("#app");
</script>
:style 디렉티브를 사용하여 textColor와 fontSize 값을 동적으로 바인딩changeStyle 메서드가 실행되어 스타일이 변경됨:class):class 디렉티브를 사용하여 CSS 클래스를 동적으로 바인딩<div id="app">
<p :class="{ 'red-text': isRed, 'bold-text': isBold }">동적으로 클래스 적용</p>
<button @click="toggleClass">클래스 토글</button>
</div>
<style>
.red-text { color: red; }
.bold-text { font-weight: bold; }
</style>
<script>
Vue.createApp({
data() {
return {
isRed: false,
isBold: false,
};
},
methods: {
toggleClass() {
this.isRed = !this.isRed;
this.isBold = !this.isBold;
},
},
}).mount("#app");
</script>
:class를 사용하여 isRed와 isBold 상태에 따라 red-text와 bold-text 클래스를 동적으로 적용<div id="app">
<button :class="[myColor, myLayout]" @click="toggleClass">테스트 버튼</button>
</div>
<style>
.blue { background-color: lightblue; color: white; }
.red { background-color: lightcoral; color: white; }
.rounded { border-radius: 10px; }
.square { border-radius: 0; }
</style>
<script src="https://unpkg.com/vue"></script>
<script>
Vue.createApp({
data() {
return { myColor: "blue", myLayout: "rounded" };
},
methods: {
toggleClass() {
this.myColor = this.myColor === "blue" ? "red" : "blue";
this.myLayout = this.myLayout === "rounded" ? "square" : "rounded";
},
},
}).mount("#app");
</script>
<button> 요소의 class 속성을 Vue 데이터 속성(myColor, myLayout)과 동적으로 연결@click="toggleClass" 버튼 클릭 시 toggleClass 메서드를 실행하여 클래스 변경| 바인딩 방식 | 예제 코드 | 설명 |
|---|---|---|
객체 형식 ({}) | :class="{ 'red-text': isRed, 'bold-text': isBold }" | 조건부로 클래스 추가/제거 |
배열 형식 ([]) | :class="[ isRed ? 'red-text' : 'blue-text', 'underline' ]" | 여러 클래스를 동적으로 적용 |
✅ 결론
[])을 사용하면 편리함{})이 유용!!computed)computed 속성을 활용computed는 반응형 데이터에 따라 스타일을 캐싱하고, 상태가 바뀔 때만 다시 계산됨computed를 이용한 동적 스타일 계산<div id="app">
<p :style="computedStyle">이 문장은 동적으로 스타일링됩니다.</p>
<button @click="toggleFontSize">폰트 크기 토글</button>
</div>
<script>
Vue.createApp({
data() {
return {
fontSize: 16,
};
},
computed: {
computedStyle() {
return {
fontSize: this.fontSize + 'px',
color: this.fontSize > 20 ? 'green' : 'blue',
};
},
},
methods: {
toggleFontSize() {
this.fontSize = this.fontSize === 16 ? 24 : 16;
},
},
}).mount("#app");
</script>
computedStyle는 fontSize 값을 기반으로 동적으로 스타일을 계산fontSize가 20px 이상이면 글씨 색은 green, 그 이하이면 blue로 설정됨:style):style을 사용하여 인라인 스타일을 객체 형태로 바인딩한다.:class):class를 사용하여 CSS 클래스를 동적으로 바인딩한다.computed)computed를 활용해 상태를 기반으로 동적으로 스타일을 계산한다.이 방법들을 조합하여 Vue.js에서 스타일을 동적으로 적용할 수 있다 !