v-bind:style 객체 구문은 매우 직설적입니다. 거의 CSS 처럼 보이지만 JavaScript 객체입니다. 속성 이름에 camelCase와 kebab-case (따옴표를 함께 사용해야 합니다)를 사용할 수 있습니다.
(vue.js공식문서)
<div v-bind:class="{ active: isActive }"></div>
active라는 class명은 data의 isActive의 값이 true 이냐 false 이냐에 따라서 달라진다.
(isACtive는 true 또는 false의 값을 가지는 토글)
ex1)
css
<style>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
template
<div id="app">
<div :class="{ red:isRed }">Hello</div>
<button @click="update">Click</button>
</div>
js
<script>
new Vue({
el: '#app',
data: {
isRed: false
},
methods: {
update() {
this.isRed = !this.isRed;
}
}
});
</script>
class는 data를 바인딩시키기 위해서 class앞에 ":"을 붙여준다. => ":class"
isRed의 값은 button의 @click으로 인한 update메소드의 실행으로 true or false 로 결정된다.
이에따라 div의 class명에 red일지 아닐지가 결정되고 "Hello"의 색이 변하게된다.
<div id="app">
<div :class="{ red:isRed, bold:isBold }">Hello</div>
<button @click="update">Click</button>
</div>
" ,"를 붙이고 더 써줄 수 있다.
<div id="app">
<div :class="{ red:isRed, "font-bold":isBold }">Hello</div>
<button @click="update">Click</button>
</div>
그 class명을 string으로 묶어주어야한다.
html
<div id="app">
<div :class="classObject">Hello</div>
<button @click="update">Click</button>
</div>
js
<script>
new Vue({
el: '#app',
data: {
classObject: {
red: true,
'font-bold':false
}
},
methods: {
update() {
this.classObject.red = !this.classObject.red;
}
}
});
</script>
위의 예제에서
classObject라는 객체를 data에 따로 만들고 각각의 class명에 값을 준 후 => 이를 class명에 써줄 수도 있다.
목록에 있는 클래스를 조건부 토글하려면 삼항 연산자를 이용할 수 있습니다.
위의 항상 errorClass를 적용하고 isActive가 true일 때만 activeClass를 적용합니다.
그러나 여러 조건부 클래스가 있는 경우 장황해질 수 있습니다.
그래서 배열 구문 내에서 객체 구문을 사용할 수 있습니다.
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
template
<div id="app">
<div :style="computedStyledObject">
Hello
</div>
<button @click="update()">Click</button>
</div>
<script>
new Vue({
el: '#app',
data: {
classObject: {
red: 'red',
size: '30px'
}
},
computed: {
computedStyledObject() {
return {
color: this.classObject.red,
size: this.classObject.size
};
}
},
methods: {
update() {
(this.classObject.red = 'blue'), (this.classObject.size = '50px');
}
}
});
</script>
위의 예제처럼 computed를 사용하여 인라인 스타일을 바인딩 할 수도 있습니다.
출처: beomy