[[📗10 ホチキスの芯はv-bind]] < [[📒Vue.jsクエスト]] > [[📗12 2つの条件属性と違い]]
## Abstract
[[Vue]]で`class`や`style`にバインドする場合は特殊な記法を使います。
## Lesson
[[v-bind]]を使うことで、`class`や`style`に変数をバインドできるようになりました。しかし、[[Vue]]で`class`や`style`に変数をバインドする場合、一般的に特殊な記法を使います。
### classにオブジェクトをバインディング
以下のように`{red: true}`をバインドすると、`class: red`と同じ意味になります。
```html
<div :class="{red: true}"></div>
<!-- ↑は↓と同じ -->
<div class="red"></div>
```
オブジェクトのプロパティ名はclass名を、値はそのclassを有効にするかどうかのbool値を示します。つまり、値が`false`のclassは指定されなかったことになります。
```html
<div :class="{red: true, blue: false}"></div>
<!-- ↑は↓と同じ -->
<div class="red"></div>
```
もちろんboolean型の[[ref()]]も割り当て可能です。
```html
<script setup lang="ts">
import { ref } from "vue";
const isRed = ref(true)
</script>
<template>
<div :class="{red: isRed}"></div>
</template>
```
### classにArrayをバインディング
class名は[[配列 (JavaScript)|配列]]で指定することもできます。場合によってはこちらの方がコードがシンプルになります。
```html
<div :class="['red', 'big']">title</div>
<!-- ↑は↓と同じ -->
<div class="red big"></div>
```
## Missions
### Misson 1
#😁EASY
以下のコードをリファクタリングしてください。
```html
<script setup lang="ts">
const classes = ["red", "big"].join(" ");
</script>
<template>
<div :class="classes">title</div>
</template>
<style>
.red {
color: red;
}
.big {
font-size: 500%;
}
</style>
```
%%
回答例
```html
<script setup lang="ts">
const classes = ["red", "big"];
</script>
<template>
<div :class="classes">title</div>
</template>
<style>
.red {
color: red;
}
.big {
font-size: 500%;
}
</style>
```
%%
### Misson 2
#🙂NORMAL
以下のコードをリファクタリングしてください。
```html
<script setup lang="ts">
import { computed } from "@vue/reactivity";
import { reactive } from "vue";
const state = reactive({
red: false,
big: false,
});
const titleStyle = computed(() =>
Object.entries(state)
.filter(([_, v]) => v)
.map(([k, _]) => k)
.join(" ")
);
</script>
<template>
<input
type="checkbox"
:checked="state.red"
@change="state.red = !state.red"
/>
<label for="red">red</label>
<input
type="checkbox"
:checked="state.big"
@change="state.big = !state.big"
/>
<label for="big">big</label>
<div :class="titleStyle">Title</div>
</template>
<style>
.red {
color: red;
}
.big {
font-size: 500%;
}
</style>
```
%%
回答例
```html
<script setup lang="ts">
import { reactive } from "vue";
const classState = reactive({
red: false,
big: false,
});
</script>
<template>
<input
type="checkbox"
:checked="classState.red"
@change="classState.red = !classState.red"
/>
<label for="red">red</label>
<input
type="checkbox"
:checked="classState.big"
@change="classState.big = !classState.big"
/>
<label for="big">big</label>
<div :class="classState">Title</div>
</template>
<style>
.red {
color: red;
}
.big {
font-size: 500%;
}
</style>
```
%%
## References
[Class and Style Bindings \| Vue\.js](https://vuejs.org/guide/essentials/class-and-style.html)