[[📗09 styleで見た目をスタイリッシュに]] < [[📒Vue.jsクエスト]] > [[📗11 Vueらしくスタイルをはめる]]
## Abstract
[[Vue]]で最もよく使う機能の1つ、属性のバインドを学びます。
## Lesson
[[v-bind]]を使うことでHTMLタグの属性に変数をバインドできます。たとえば以下のコードについて。
```html
<template>
<img height="100" src="xxx" />
</template>
```
`height`に変数を割り当てる場合は以下のように書き換え可能です。
```html
<script setup lang="ts">
const imgHeight = 100;
</script>
<template>
<img v-bind:height="imgHeight" src="xxx" />
</template>
```
また、`v-bind`は省略可能です。つまり、以下のように書けます。
```html
<script setup lang="ts">
const imgHeight = 100;
</script>
<template>
<img :height="imgHeight" src="xxx" />
</template>
```
`:`はホチキスの芯みたいですね。バインダーとbindがかかっているのかもしれません。もちろん定数以外にも[[ref()]]や[[reactive()]]、[[computed()]]などを割り当てられます。
## Missions
### Misson 1
#🙂NORMAL
ボタンを押すたびに画像の高さが`10px`ずつ増加するように以下のコードを改変してください。
```html
<script setup lang="ts">
const imgHeight = 100;
</script>
<template>
<img
:height="imgHeight"
src="https://publish-01.obsidian.md/access/35d05cd1bf5cc500e11cc8ba57daaf88/Notes/attachments/Pasted%20image%2020210605212134.png"
/>
</template>
```
%%
回答例
```html
<script setup lang="ts">
import { ref } from "vue";
const imgHeight = ref(100);
const handleClick = () => {
imgHeight.value += 10;
};
</script>
<template>
<div>
<button @click="handleClick">高さを増やす</button>
</div>
<img
:height="imgHeight"
src="https://publish-01.obsidian.md/access/35d05cd1bf5cc500e11cc8ba57daaf88/Notes/attachments/Pasted%20image%2020210605212134.png"
/>
</template>
```
%%
### Misson 2
#😵HARD
クリックするたびに色の変わる文字を実装してください。
%%
回答例
```html
<script setup lang="ts">
import { Ref, ref } from "vue";
const colors = ["red", "green", "blue"] as const;
type Color = typeof colors[number];
const color: Ref<Color> = ref("red");
const cycleColor = (color: Color): Color => {
switch (color) {
case "red":
return "green";
case "green":
return "blue";
case "blue":
return "red";
}
};
const handleClick = () => {
color.value = cycleColor(color.value);
};
</script>
<template>
<div @click="handleClick" :style="`color: ${color}; cursor: pointer`">
クリックすると色が変わるよ
</div>
</template>
```
%%
> [!hint]- Hint 1
> [[📗09 styleで見た目をスタイリッシュに]] で学んだ技術を使います。
## References
[Template Syntax \| Vue\.js](https://vuejs.org/guide/essentials/template-syntax.html#attribute-bindings)