⚠️ 이 포스팅은 Vue3(한국어): 클래스와 스타일 바인딩을 공부하고 정리한 블로그 포스팅입니다. ⚠️
- HTML 클래스 바인딩
- 인라인 스타일 바인딩하기
클래스 바인딩
객체 구문 (인라인)
객체를 data에 정의해서 class에 연결해줄 수도 있다.
<template>
<h1 v-bind:class="{ active: isActive }" @click="activate">
Hello
</h1>
</template>
<script>
export default {
data() {
return {
isActive: false,
};
},
methods: {
activate() {
this.isActive = true;
},
},
};
</script>
<style scoped>
.active {
font-weight: bold;
}
</style>
객체 구문 (객체 따로 빼주기)
클래스 이름 text-danger를 작은따옴표로 묶어서 object의 key값으로 사용할 수 있도록 해주었다.
<template>
<h1 v-bind:class="classObject" @click="activate">Hello</h1>
</template>
<script>
export default {
data() {
return {
classObject: {
active: false,
'text-danger': false,
},
};
},
methods: {
activate() {
this.classObject.active = true;
this.classObject['text-danger'] = true;
},
},
};
</script>
<style scoped>
.active {
text-decoration: underline;
}
.textDanger {
color: red;
}
</style>
배열 구문
<template>
<h1 v-bind:class="[activeClass, errorClass]" @click="activate">Hello</h1>
</template>
<script>
export default {
data() {
return {
activeClass: 'active',
errorClass: 'text-danger',
};
},
};
</script>
<style scoped>
.active {
text-decoration: underline;
}
.text-danger {
color: red;
}
</style>
스타일 바인딩
CSS 속성 이름에는 카멜 케이스(camelCase) 또는 케밥 케이스(kebab-case)를 사용할 수 있다. 케밥 케이스를 사용하면 작은따옴표로 감싸주어야하는 번거로움이 있기 때문에 그냥 카멜케이스로 사용하자.
<template>
<h1 :style="{ color: color, 'font-size': fontSize }" @click="changeStyle">
Hello
</h1>
</template>
객체 구문
<template>
<h1 :style="{ color: color, fontSize: fontSize }" @click="changeStyle">
Hello
</h1>
</template>
<script>
export default {
data() {
return {
color: 'orange',
fontSize: '30px',
};
},
methods: {
changeStyle() {
this.color = 'red';
this.fontSize = '50px';
},
},
};
</script>
배열 구문
<template>
<h1 :style="[fontStyle, backgroundStyle]" @click="changeStyle">Hello</h1>
</template>
<script>
export default {
data() {
return {
fontStyle: {
color: 'orange',
fontSize: '30px',
},
backgroundStyle: {
backgroundColor: 'black',
},
};
},
methods: {
changeStyle() {
this.fontStyle.color = 'red';
this.fontStyle.fontSize = '50px';
},
},
};
</script>'Vue' 카테고리의 다른 글
| [Vue] 리스트 렌더링 (v-for) (0) | 2022.06.14 |
|---|---|
| [Vue] 조건부 렌더링 v-if, v-else, v-else-if, v-show (v-if와 v-show의 차이점) (0) | 2022.06.14 |
| [Vue] Watch 속성 정리 (0) | 2022.06.13 |
| [Vue] Computed 속성의 Getter와 Setter (0) | 2022.06.12 |
| [Vue] Computed 속성과 Computed 캐싱 (0) | 2022.06.12 |
댓글