0
0

More than 1 year has passed since last update.

【Vue.js】Computed, Watchの使い分け

Posted at

この記事の目的

PRでレビューをいただいた際に疑問に思ったため、アウトプット用
独自の解釈もあるので、間違いがあればご指摘をいただきたいです!

どう分けるのか

基本的にはcomputedの方が簡潔に記述できるから良い
computed内に記述されている変数は依存関係になっている
watchは依存関係(監視する変数)を宣言しないと監視できない(コードが冗長になる)

watch: {
    firstName(val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName(val) {
      this.fullName = this.firstName + ' ' + val
    }
}

firstName, lastNameは同時にwatchすることも可能

computed: {
    fullName() {
      return this.firstName + ' ' + this.lastName
    }
  }

firstName, lastNameは特に宣言しなくても依存関係になる(監視)

以下の場合はwatchの方が良い

  • 非同期で値を使うとき(axiosでの値取得など)
  • 更新前と更新後の値を使う場合
  • 処理を実行するだけ(returnしない)の時

参考文献

Vue公式ドキュメント
【Vue.js】computedとwatchの違い・使い分け

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