[[📗06 状態で広がるセカイ reactive編]] < [[📒Vue.jsクエスト]] > [[📗08 computedの使いどころ]] ## Abstract [[Computed property]]をマスターしてテンプレートの可読性を上げましょう。 ## Lesson 以下は2つの数を足し合わせた結果を表示するコードです。 ```html <script setup lang="ts"> import { computed, ref } from "vue"; const x = ref(0); const y = ref(0); const result = ref(0); const incrementX = () => { x.value++; result.value = x.value + y.value; }; const incrementY = () => { y.value++; result.value = x.value + y.value; }; </script> <template> <div>{{ x }} + {{ y }} = {{ result }}</div> <button @click="incrementX">xを増やす</button> <button @click="incrementY">yを増やす</button> </template> ``` このコードでは`incrementX`と`incrementY`の中で`result`の再計算を行っています。この書き方には2つのデメリットがあります。 - 都度処理を書くのが面倒で冗長 (関数化しても) - 処理を忘れたら正しい結果が表示されない [[computed()]]を使うとこの問題を解決できます。 ```html <script setup lang="ts"> import { computed, ref } from "vue"; const x = ref(0); const y = ref(0); const incrementX = () => { x.value++; }; const incrementY = () => { y.value++; }; const result = computed(() => x.value + y.value); </script> <template> <div>{{ x }} + {{ y }} = {{ result }}</div> <button @click="incrementX">xを増やす</button> <button @click="incrementY">yを増やす</button> </template> ``` 以下の部分に注目してください。 ```ts const result = computed(() => x.value + y.value); ``` この一文で、**『`x`または`y`に変更があった場合、`result`を再計算させる』** 効果があります。一般化すると以下のようになります。 ```ts const result = computed(<引数なし、計算結果をreturnする関数>); ``` ## Missions ### Mission 1 #😁EASY [[computed()]]を使った意味のあるコードを書いてください。 %% 回答例 - [[computed()]]を使う意味があるコードならなんでもOK %% ### Mission 2 #🙂NORMAL 以下のコードが正しく動くよう修正してください。 ```html <script setup lang="ts"> import { computed, ref } from "vue"; const x = ref(0); const y = ref(0); const incrementX = () => { x.value++; }; const incrementY = () => { y.value++; }; const result1 = computed(() => x.value + y.value); const result2 = computed(() => result1 * 2); </script> <template> <div>{{ x }} + {{ y }} = {{ result1 }}</div> <div>({{ x }} + {{ y }}) * 2 = {{ result2 }}</div> <button @click="incrementX">xを増やす</button> <button @click="incrementY">yを増やす</button> </template> ``` %% 回答例 ```html <script setup lang="ts"> import { computed, ref } from "vue"; const x = ref(0); const y = ref(0); const incrementX = () => { x.value++; }; const incrementY = () => { y.value++; }; const result1 = computed(() => x.value + y.value); const result2 = computed(() => result1.value * 2); </script> <template> <div>{{ x }} + {{ y }} = {{ result1 }}</div> <div>({{ x }} + {{ y }}) * 2 = {{ result2 }}</div> <button @click="incrementX">xを増やす</button> <button @click="incrementY">yを増やす</button> </template> ``` %% ### Mission 3 #😵HARD [[#Mission 2]]のコードと回答について、以下の問いに答えてください。 1. 修正前、エラーになっていた理由 2. `<template>`内では同様の修正が不要な理由 %% 回答例 1. `result1`は`number`ではなく`ComputedRefImpl`だから 2. `<template>`内では自動でunwrapされるため %% ## References [Computed Properties \| Vue\.js](https://vuejs.org/guide/essentials/computed.html)