데일리 공부 기록
hands on vue - 선택에 따른 class 추가
탐훈
2023. 3. 1. 19:47
728x90
[Lesson 34]
1. 박스 세개를 만들고 클릭했을 때 "active"라는 클래스를 추가하여 색상을 변경하라
변경된 색상의 박스를 한번 더 클릭하면 원래 색상으로 돌아가는 토글 기능을 생성하라
.active{
border-color: red;
background-color: salmon;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/vue@next" defer></script>
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>Vue Dynamic Styling</h1>
</header>
<section id="styling">
<div class="demo" v-bind:class="{active : boxASelected}" v-on:click="selectedBox('A')"></div>
<div class="demo" v-bind:class="{active : boxBSelected}" v-on:click="selectedBox('B')"></div>
<div class="demo" v-bind:class="{active : boxCSelected}" v-on:click="selectedBox('C')"></div>
</section>
</body>
</html>
const app = Vue.createApp({
data: function(){
return{
boxASelected: false,
boxBSelected: false,
boxCSelected: false,
}
},
methods: {
selectedBox(box){
console.log('boxboxbox');
console.log(box);
if(box === 'A') {
this.boxASelected = !this.boxASelected; //Wow...
} else if(box === 'B') {
this.boxBSelected = !this.boxBSelected; //Wow...
} else if(box === 'C') {
this.boxCSelected = !this.boxCSelected; //Wow...
}
}
},
watch: {
},
}).mount('#styling');
토글키를 어떻게 구현할까 고민하다가 결국에는 강사의 코드를 보았다.
기존의 boxSelected 참 거짓으로 확인하여 로직을 만들었는데 정말 심플하고 놀라웠다...