1. 클래스와 스타일 바인딩(v-bind:class)
Vue에서는 class를 적용할 때 v-bind를 이용하여 표현을 할 수 있습니다. 표현식은 문자열, 객체 또는 배열을 사용할 수 있습니다.
2. 사용 예제
- 객체 구문
- class 자체에 key, value 형식의 객체를 표현할 수 있습니다. data에 정의할 수도 있고 computed 속성에 정의할 수도 있습니다. v-bind:class에 value값을 직접 지정해 주는 것도 가능합니다.
<template>
<h3>data에 정의</h3>
<h3 v-bind:class="{active: isActive, error: hasError}" v-on:click="activate">
Hello?!
</h3>
<h3>computed에 정의</h3>
<h3 v-bind:class="classObject" v-on:click="activate">Hello?!</h3>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false,
};
},
computed: {
classObject() {
return {
active: this.isActive,
error: !this.hasError,
};
},
},
methods: {
activate() {
this.isActive = true;
},
},
};
</script>
<style scoped>
.active {
color: blue;
font-weight: bold;
}
.error {
color: red;
}
</style>
data에 정의한 isActive와 hasError는 true, false로 해당 dom의 class는 active입니다. 반면에 computed에서 연산한 classObject 객체의 isActive와 hasError는 true, true로 해당 dom의 class가 active error임을 확인할 수 있습니다.
- 배열 구문
- 배열을 class에 전달하여 표현할 수도 있습니다.
<template>
...
<h3>배열로 정의</h3>
<h3 v-bind:class="[activeClass, errorClass]">Hello?!</h3>
</template>
<script>
export default {
data() {
return {
...
activeClass: 'active',
errorClass: 'error'
};
},
computed: {
...
},
methods: {
...
},
};
</script>
<style scoped>
...
</style>
이 처럼 class에 배열을 통해 여러개의 클래스를 지정할 수 있습니다. 배열 안에는 삼항 연산자도 사용할 수 있습니다.
<h3 v-bind:class="[isActive ? activeClass : '', hasError ? errorClaass : '']" >Hello?!</h3>
3. 인라인 스타일 바인딩(v-bind:style)
Vue에서는 style를 적용할 때 v-bind를 이용하여 표현을 할 수 있습니다. 표현식은 문자열, 객체 또는 배열을 사용할 수 있습니다.
4. 사용 예제
- 객체 구문
- 클래스 바인딩과 마찬가지로 style의 속성을 key, value 값 형태인 객체를 표현하여 style을 지정해 줄 수 있습니다. 속성 이름엔 camelCase 혹은 따옴표와 함께 kebab-case를 사용할 수 있습니다. v-bind:class에 속성 값을 직접 지정해 줄 수도 있습니다.
<template>
...
<h3>객체로 정의</h3>
<h3 v-bind:style="{color: 'blue', backgroundColor}">Hello?!</h3>
</template>
<script>
export default {
data() {
return {
...
backgroundColor: 'black'
};
},
computed: {
...
},
methods: {
...
},
};
</script>
<style scoped>
...
</style>
클래스 바인딩과 마찬가지로 data에 정의하여 값을 지정해 줄 수 있고, computed로 연산하여 값을 지정해 줄 수도 있습니다. 객체를 반환하여 사용할 수도 있습니다.
- 배열 구문
- 배열 구문을 사용하여 같은 스타일의 엘리먼트에 여러 개의 스타일 객체를 사용할 수 있습니다.
<template>
...
<h3 v-bind:style="[style1, style2]">Hello?!</h3>
</template>
<script>
export default {
data() {
return {
...
style1: {
color: 'yellow'
},
style2: {
backgroundColor: 'red',
}
};
},
computed: {
...
},
methods: {
...
},
};
</script>
<style scoped>
...
</style>
참고 문서:
'Front-end > Vue' 카테고리의 다른 글
Vue.js) 리스트 렌더링 (0) | 2024.07.25 |
---|---|
Vue.js) 조건부 렌더링 (0) | 2024.07.25 |
Vue.js) Watch (0) | 2024.07.24 |
Vue.js) Getter, Setter (0) | 2024.07.24 |
Vue.js) Computed 캐싱 (0) | 2024.07.24 |