LoginSignup
0
0

More than 1 year has passed since last update.

【Vue.js】算出プロパティと監視プロパティの比較

Posted at

はじめに

こんにちは!
今回は【Vue.js】算出プロパティと監視プロパティについて比較していきます!

算出プロパティ VS 監視プロパティ

算出プロパティと監視プロパティどちらでも実装できてしまう場合、基本的には算出プロパティを利用することを推奨されている。理由としてはシンプルに記述することができるからである。

書き方・解説

今回は以下のように、firstNameテキストlastNameテキストを入力したら
fullName: firstName スペース lastName
と表示されるようにしていきます。
これを算出プロパティ監視プロパティで記述し比較していきます。

スクリーンショット 2021-10-19 20.51.54.png

HTML
<div id="app">
  <p>
    firstName: <input type="text" v-model:value="firstName">
  </p>
  <p>
    lastName: <input type="text" v-model:value="lastName">
  </p>
  <p>
    fullName: {{ fullName }}
  </p>
</div>

HTMLはどちらも変わらず。

⏬算出プロパティ

Vue.js
var app = new Vue({
  el: "#app",
  data: {
    firstName: '',
    lastName: ''
  },
  computed: {
    fullName: function() {
    return this.firstName + ' ' + this.lastName
    }
  }
})

⏬監視プロパティ

Vue.js
 var app = new Vue({
  el: "#app",
  data: {
    firstName: '',
    lastName: '',
    fullName: ''
  },
  watch: {
    firstName: function(value) {
      this.fullName = value + ' ' + this.lastName
    },
    lastName: function(value) {
      this.fullName = this.firstName + ' ' + value
    }
  }
})  

このようにどちらでも処理を実行できる場合、算出プロパティの方がコード量が少なくスッキリと記述できます。

まとめ

どちらでも記述できる場合、算出プロパティで実行しましょう。

最後に

今回は算出プロパティと監視プロパティの比較についてアウトプットしました。
今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。

今後ともQiitaにてアウトプットしていきます!

最後までご愛読ありがとうございました!

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