클래스 속성에 데이터 연결하는 법을 알아보자!
클래스 속성에 데이터를 연결해 동적인 스타일을 주고 싶을 때는 v-bind와 객체 리터럴을 사용하면 된다.
<style>
.title {
font-size: 60px;
color: blue;
}
.active {
color: red;
}
.small {
font-size: 40px;
}
</style>
<div id="app">
<button @click="toggle">Toggle</button>
<h1 :class="{active, small}" class="title">{{msg}}</h1>
</div>
const App = {
data() {
return {
msg: "Hello Vue!",
active: false,
small: true,
};
},
methods: {
toggle() {
this.active = !this.active;
},
},
};
const vm = Vue.createApp(App).mount("#app");
데이터가 false일때는 공백을 반환하고, true일때는 각각 key값을 반환한다.
기본적으로 h1태그의 클래스는 title이지만 active 값과 small 값에 따라 active small title, active title, small title 등과 같이 클래스를 동적으로 추가할 수 있다.
<h1 :class="{active, 'title--small color--orange': small}" class="title">
{{msg}}
</h1>

기본적으로 클래스를 - 같은 특수문자로 이어서 쓰게 되면 CamelCase로 인식하기 때문에 '를 사용하였고, 띄어쓰기를 통해 클래스를 두개로 나눠서 두 클래스에 동시에 small 값을 바인딩 하는것이 가능하다.
<div id="app">
<button @click="changeTitle">Toggle</button>
<h1 :class="[active, title]">Hello Vue!</h1>
</div>
const App = {
data() {
return {
active: "active",
title: "title",
};
},
methods: {
changeTitle() {
this.title = "title--large";
},
},
};
const vm = Vue.createApp(App).mount("#app");
위와 같이 배열 데이터도 동적으로 바인딩 가능하다.
통상적으로 인라인 스타일은 권장되지 않지만 의외로 동적 바인딩을 통해 스타일을 줄 때는 인라인 스타일을 이용하고 나머지는 선택자를 이용해 스타일을 하는 것이 권장되는 방법이다.
<style>
h1 {
border: 4px solid;
}
</style>
<div id="app">
<h1 :style="{color, backgroundColor}">Hello Vue!</h1>
</div>
const App = {
data() {
return {
color: "royalblue",
backgroundColor: "orange",
};
},
};
const vm = Vue.createApp(App).mount("#app");
또한 인라인 스타일 바인딩의 장점으로는 스타일 내부에서 속성을 굳이 따옴표를 사용하지않고 camelCase로 작성하여 편리하다는 점이 있다.
여러 개의 객체 데이터를 태그에 바인딩할때 배열 데이터로 묶어서 편리하게 구현할 수 있다.
<style>
h1 {
border: 4px solid;
}
</style>
<div id="app">
<h1 :style="[styleObject, titleStyleObject]">Hello Vue!</h1>
</div>
const App = {
data() {
return {
styleObject: {
color: "royalblue",
backgroundColor: "orange",
},
titleStyleObject: {
fontSize: "40px",
fontWeight: "bold",
},
};
},
};
const vm = Vue.createApp(App).mount("#app");
