vue.js入門_12_監視プロパティ(算出プロパティとの違い)

by s9iwork

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>

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>

JavaScript

// 監視プロパティ
/*
new Vue({
  el: '#app',
  data: {
    lastName: '',
    firstName: '',
    fullName: '',
  },
  watch: {
    firstName: function(value) {
      this.fullName = value + ' ' + this.lastName
    },
    lastName: function(value) {
      this.fullName = this.firstName + ' ' + value
    }
  },
})
*/

// 算出プロパティ
new Vue({
  el: '#app',
  data: {
    lastName: '',
    firstName: '',
  },
  computed: {
    fullName: function() {
      return this.firstName + ' ' + this.lastName
    }
  },
})