
한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online를 들으며 정리한 내용입니다.
화면에서 Hello?!라는 글자를 입력하면, isActive라는 데이터가 false에서 true로 바뀌게 됩니다.
<template>
<h1 @click="activate">
Hello?! ({{ isActive }})
</h1>
</template>
<script>
export default {
data() {
return {
isActive: false
}
},
methods: {
activate() {
this.isActive = true
}
}
}
</script>

글자를 누르면 (false)가 (true)로 바뀌는 것을 확인할 수 있습니다.
<style scoped>
.active {
color: red;
font-weight: bold;
}
</style>
active라는 클래스가 있는 경우에만 해당하는 스타일이 적용될 수 있기 때문에 template부분도 함께 수정을 해줍니다.
<template>
<h1
:class="{ active: isActive }"// {key: value}는 데이터이기 때문에 데이터를 취급할 수 있도록 v-bind디렉티브를 넣어줍니다.(약어:)
@click="activate">
Hello?!({{ isActive }})
</h1>
</template>
h1의 클래스로 active라는 이름의 클래스를 추가합니다. 이 때 클래스의 이름은 isActive의 영향을 받아서 boolean데이터 true인 경우 클래스가 추가될 수 있고, boolean데이터 false인 경우 클래스가 추가될 수 없는 구조를 만들어주었습니다. 이를 클래스 바인딩이라고 합니다.
클래스를 동적으로 토글하기 위해 객체를 :class(v-bind:class의 약어) 전달할 수 있습니다.
//하나의 클래스 전달
<div :class="{ active: isActive }"></div>
//여러 클래스 전달
<div
class="static"
:class="{ active: isActive, 'text-danger': hasError }"
></div>
data의 isActive의 값이 true 이냐 false 이냐에 따라서class명은 달라지게 됩니다.
✔️바인딩 객체는 꼭 인라인일 필요는 없으며, data뿐만 아니라 computed property에 바인딩할 수도 있습니다.
<div :class="classObject"></div>
//data에 바인딩한 경우
data() {
return {
classObject: {
active: true,
'text-danger': false
}
}
}
//computed poperty에 바인딩한 경우
data() {
return {
isActive: true,
error: null
}
},
computed: {
classObject() {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
배열을 :class에 전달하여 클래스 목록을 적용할 수도 있습니다.
<div :class="[activeClass, errorClass]"></div>
data() {
return {
activeClass: 'active',
errorClass: 'text-danger'
}
}
//렌더링결과
<div class="active text-danger"></div>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
객체 데이터 자체를 바인딩하는 것이 깔끔합니다.
<div :style="styleObject"></div>
data() {
return {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
}
<template>
<h1
:style="{ color, fontSize }" //key, value가 같아서 value생략.
@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' //객체데이터 안에 있는 color를 변경
this.fontStyle.fontSize='50px'
}
}
}
</script>