Blog>
Snippets

Reactive Dependency Tracking with `computed`

Explain dependency tracking by creating a reactive `computed` property that updates when its dependencies change.
<html>
  <head>
    <title>Computed Example</title>
    <style>
      #app {
        margin: 2rem;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <input v-model="firstName" placeholder="First Name">
      <input v-model="lastName" placeholder="Last Name">
      <p>Full Name: {{ fullName }}</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script>
      new Vue({
        el: '#app',
        data: {
          firstName: '',
          lastName: ''
        },
        computed: {
          // computed property 'fullName' depending on 'firstName' and 'lastName'
          fullName: function() {
            return this.firstName + ' ' + this.lastName;
          }
        }
      });
    </script>
  </body>
</html>
HTML with Vue.js: Input fields are bound to reactive data properties (firstName and lastName). A computed property (fullName) is declared which combines these and updates automatically when either dependency changes.