0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「Vue完全攻略への道」Day15-computed

Posted at

〇背景

Vue を使っていると値の表示ロジック(整形・集計・フィルタ)が増える。

そのたびにテンプレートへ直接書くと可読性が落ちるし、計算を何度も実行してムダも出る。

computed は “元データから導かれる値(派生状態)” を宣言的に定義し、必要な時だけ再計算してくれる仕組み。

よく ref と混同しがちなので、違いも整理する。


〇今回のコード例

<script setup lang="ts">
import { ref, computed } from 'vue'

const first = ref('山田')
const last  = ref('太郎')

// 読み取り専用の派生値(キャッシュされる)
const fullName = computed(() => `${last.value} ${first.value}`)

// 書き込み可能(getter/setter)
const taxRate = ref(0.1)
const price   = ref(1000)
const priceWithTax = computed({
  get: () => Math.round(price.value * (1 + taxRate.value)),
  set: (v: number) => {
    // 逆算して素の price を調整する例(実務では注意)
    price.value = Math.round(v / (1 + taxRate.value))
  }
})
</script>

<template>
  <p>{{ fullName }}</p>
  <p>税込価格: {{ priceWithTax }}</p>
</template>


〇調べる前の自分の認識

  • computed はなんとなく “自動で更新される値”。
  • ref もリアクティブだから似てる気がする…違いはよく分からない。
  • methods と何が違うの?毎回呼ぶのとどう違う?

〇調べた結果

  • ref“一次データ(状態そのもの)” を保持するリアクティブな箱(.value)。

    • 例:入力値、APIで取得した配列、フラグなど。
  • computed“一次データから計算で導く派生データ” を宣言。

    • 依存している ref/reactive/computed が変わった時だけ再計算。
    • 結果はキャッシュされ、依存に変化がなければ再利用。
  • computedmethods の違い

    • methods は呼ぶたびに実行(キャッシュなし)。
    • computed は依存が変わらない限り再実行されず高速。
  • 書き込み可能な computed(getter/setter)も作れるが、多用は非推奨。

    “派生は読み取り専用” が基本設計としては扱いやすい。


〇動作解説(図解やコメント付きコード)

一次データ(ref/reactive)
          │ 依存
          ▼
     [ computed ]
     (キャッシュ)
          │ 値を参照
          ▼
       テンプレート / ロジック

キャッシュのメリット例

const list = ref([/* 大量データ */])
const expensiveFiltered = computed(() => {
  // 重いフィルタ処理
  return list.value.filter(/* ... */)
})

// テンプレートで複数回使っても再計算は1回(依存が不変なら)

methods との比較

// 毎回実行(キャッシュなし)
function filteredNow() {
  return list.value.filter(/* ... */)
}


〇実務での注意点

  1. “データの源泉” は ref/reactive見せ方/集計” は computed に分離する。
  2. 副作用を computed に入れない。(API 呼び出し、DOM 操作、外部書き込みなど)
    • 副作用は watch / watchEffect に逃がす。
  3. 書き込み可能 computed は慎重に。
    • 双方向っぽい設計は依存関係を複雑にする。できれば読み取り専用に。
  4. パフォーマンスを意識。
    • 重い処理こそ computed にしてキャッシュの恩恵を受ける。
  5. テンプレートをスリムに。
    • 長い三項・複雑な式は computed に切り出して可読性を上げる。
  6. 依存が正しくトラッキングされる書き方にする。
    • 例:someRef.value をちゃんと参照する。参照漏れは更新されない原因に。

〇まとめ・所感

  • ref は“元データの箱”、computed は“元データから導く派生値”。
  • computed依存に基づき自動再計算 + キャッシュ が本質。
  • 「状態は ref に、表示や集計は computed に」—この分担を守ると、可読性・テスト容易性・パフォーマンスが揃って向上する。
  • methods と迷ったら、「同じ入力が続く場面で再計算を避けたいか?」で判断するとよい。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?