Introduction to Computed Properties in Vue.js

Computed properties can be used to do quick calculations of properties that are displayed in the view. These calculations will be cached and will only update when needed.

There are a lot of ways to bind or display data in the HTML template in Vue.js. As we discussed in Vue js templating. Computed properties provide a very intuitive way that binds the template with variables that are computed depending upon other variables or conditions. Vue re-renders these bound variables automatically if any of those variable used inside its computation is updated anytime.

Computed Properties

Computed properties allow us to have model-specific, complex values computed for the view. These values will be bound to the dependency values and only update when required.

Let us say we have an array of items with their quantities and we have to show their sum somewhere in our template.

data() {
  return {
    items: [
      	{
          name: 'Box',
          qty: 70
        },
        {
          name: 'Stick',
          qty: 80
        },
        {
          name: 'Rubber',
          qty: 90
        }
      ]
  }
}

Now to calculate the sum of all quantities we can use a computed variable like this.

computed: {
  totalQty: function() {
    let total = 0;
    for(let i = 0; i < this.items.length; i++){
      total += parseInt(this.items[i].qty);
    }
    return total;
  }
}

The totalQty computed property calculates the total quantity using the items array. It simply loops through the values and returns the sub total.

Now, we can display the computed value in the view:

<div id="app">
  <div v-for="item in items">
    <input v-model="item.qty">
    <span>
      Quantity for {{ item.name }}: {{ item.qty }}
    </span>
  </div>

  <span>
    Total count is: {{ totalQty }}
  </span>
</div>

Computed Properties vs Methods

We can get the same result by using a method that outputs the total quantity in the same way.

While this gives the same output, but it gives a performance hit. Using this syntax, the totalQty() the method gets executed every time the page renders due to any change.

If instead, we had a computed property, Vue remembers the values that the computed property is dependent on (ex: In the previous example, that would be items). By doing so, Vue can calculate the values only if the dependency changes. Otherwise, the previously cached values will be returned.

Therefore, the function must be a pure function. It can’t have side-effects. The output must only be dependent on the values passed into the function.

Computed Setters

By default, the computed properties only present a getter method. But, it’s also possible to declare the setters method for the same properties. For example

computed: {
  fullName: {
    get: function() {
      return this.firstName + this.lastName;
    },
    set: function(value) {
      let names = value.split(' ');
      this.firstName = names[0];
      this.lastName = names[1];
    }
  }
}

By having both getters and setters, we can bind the input value correctly to the data property. If we set the fullName in a method, the passed-in string will be split into the first and last name. This way we automatically set the data properties of first name and last name.

Watchers Vue js

Computed properties are sufficient in almost all cases, watchers provide an additional level of control by allowing us to listen for changes to any given property.

Watchers, allows us to watch for changes in a data object. Watchers are more complex and expensive than computed properties.

We can use watchers for more complex requirements, such as:

  • Async operations
  • Setting intermediate values
  • Limiting the number of times an operation gets called (ex: Debounce an input event)

What’s next

Next, you can learn about events vue js.

Imad

I am a Software Engineer with ample experience in making games, websites, mobile apps and augmented reality solutions.

Pin It on Pinterest