computed 속성을 사용하여 적용이 가능하다.
<!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
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>Vue Dynamic Styling</h1>
</header>
<section id="styling">
<div
class="demo"
:class="boxAClasses"
@click="boxSelected('A')"
></div>
<div
class="demo"
:class="boxBClasses"
@click="boxSelected('B')"
></div>
<div
class="demo"
:class="boxCClasses"
@click="boxSelected('C')"
></div>
</section>
</body>
</html>
아래는 app.js 코드
const app = Vue.createApp({
data() {
return {
boxASelected: false,
boxBSelected: false,
boxCSelected: false
};
},
computed: {
boxAClasses () {
return { active: this.boxASelected };
},
boxBClasses () {
return { active: this.boxBSelected };
},
boxCClasses () {
return { active: this.boxCSelected };
},
},
methods: {
boxSelected(box) {
if (box === 'A') {
this.boxASelected = !this.boxASelected;
} else if (box === 'B' ) {
this.boxBSelected = !this.boxBSelected;
} else if (box === 'C') {
this.boxCSelected = !this.boxCSelected;
}
}
}
});
app.mount('#styling');
또는..
<!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
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>Vue Dynamic Styling</h1>
</header>
<section id="styling">
<div
:class="['demo', {active: boxASelected}]"
@click="boxSelected('A')"
></div>
<div
:class="['demo', {active: boxBSelected}]"
@click="boxSelected('B')"
></div>
<div
:class="['demo', {active: boxCSelected}]"
@click="boxSelected('C')"
></div>
</section>
</body>
</html>
으로 구성할 수 도 있다.
'WEB Developer > Vue JS' 카테고리의 다른 글
v-if, v-for, list 예시 (0) | 2024.03.31 |
---|---|
Rendering Content Conditionally (v-if, v-show, v-for) (1) | 2024.03.31 |
v-bind 사용 - Dynamic Styling (Click 시 색상 변화) (0) | 2024.03.30 |
08. v-bind and v-on shorthands (0) | 2024.03.30 |
Methods vs Computed vs Watch (0) | 2024.03.30 |