Vue.js

Vue.jsのcomputed

kurumin

computedって何?

<script setup>
import { ref, computed } from 'vue'
let score = ref(0)
const evaluation = computed(() => {
  console.log('computed')
  return score.value > 3 ? 'Good' : 'Bad'
})
</script>

<template>
  <p>{{ score > 3 ? 'Good' : 'Bad' }}</p>
  <p>{{ evaluation }}</p>
  <p>{{ score }}</p>
  <button @click="score++">+1</button>
</template>

computed関数の引数は関数を書く。

computed関数は常に監視され、その中に記述したリアクティブな値が変更されたときに、関数が実行される(リアクティブエフェクト

普通の関数とcomputed関数

<script setup>
import { ref } from 'vue'
let score = ref(0)
const evaluation = () => {
  return score.value > 3 ? 'Good' : 'Bad'
}
</script>

<template>
  <p>{{ score > 3 ? 'Good' : 'Bad' }}</p>
  <p>{{ evaluation() }}</p>
  <p>{{ score }}</p>
  <button @click="score++">+1</button>
</template>

テンプレート内で関数呼び出しした場合も動作はするが、computed関数を使用するようにする。

関数呼び出しの場合、score以外の値が変わった場合なども、闇雲に毎回再レンダリングごとに実行されてしまうため。

注意点

値の変更ができない

読み取り専用であり、値の変更をすることはできない。

▼ダメな例

evaluation.value = 'hello'

computed関数の中で値の変更はしない(推奨)

技術的には可能だが、computed関数の中で副作用を与えることは避ける。

const evaluation = computed(() => {
  console.log('computed')
  score.value = 0
  return score.value > 3 ? 'Good' : 'Bad'
})

非同期の処理も副作用になるので含まないようにする。

computedは常にデータを綺麗にまとめてriternで返すくらいの処理を書くようにする。

ABOUT ME
記事URLをコピーしました