Blog>
Snippets

Tracking reactive dependencies with computed properties

Show how to define a computed property that automatically updates when its reactive dependencies change.
<div id='app'>
  <input v-model='firstName' placeholder='First Name' />
  <input v-model='lastName' placeholder='Last Name' />
  <p>Full name: {{ fullName }}</p>
</div>
HTML structure with Vue.js directives. Binds the firstName and lastName to input fields and displays the computed fullName.
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
Including Vue.js from a CDN for simplicity. In a production environment, one might use npm instead.
<style>
  input {
    display: block;
    margin-bottom: 10px;
  }
</style>
Basic CSS to style the input elements. Each input is displayed as a block and has a margin bottom.
new Vue({
  el: '#app',
  data: function() {
    return {
      firstName: '',
      lastName: ''
    };
  },
  computed: {
    fullName: function() {
      // This computed property depends on firstName and lastName.
      // Whenever either of them changes, this property is re-evaluated.
      return this.firstName + ' ' + this.lastName;
    }
  }
});
The Vue instance binding to the #app element, with firstName and lastName data being reactive properties, and fullName being a computed property which changes when either firstName or lastName changes.