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 multiple ways in Vue to set values for the view. This includes directly binding data value to the view, using simple expressions or using filters to do simple transformations on the content. In addition to this, we can use computed properties to calculate display value based on a value or a set of values in the data model.

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.

For example, we can have an array of subject results in the data model:

data() {
  return {
    results: [
      	{
          name: 'English',
          marks: 70
        },
        {
          name: 'Math',
          marks: 80
        },
        {
          name: 'History',
          marks: 90
        }
      ]
  }
}

Assume that we want to view the total for all subjects. We can’t use filters or expressions for this task.

  • Filters are used for simple data formatting and that are needed at multiple places in the application.
  • Expressions don’t allow the use of flow operation or other complex logic. They should be kept simple.

Here’s where computed properties come in handy. We can add a computed value to the model like this:

computed: {
  totalMarks: function() {
    let total = 0;
    for(let i = 0; i < this.results.length; i++){
      total += parseInt(this.results[i].marks);
    }
    return total;
  }
}

The totalMarks computed property calculates the total marks using the results array. It simply loops through the values and returns the sub total.

We can then display the computed value in the view:

<div id="app">
  <div v-for="subject in results">
    <input v-model="subject.marks">
    <span>
      Marks for {{ subject.title }}: {{ subject.marks }}
    </span>
  </div>

  <span>
    Total marks are: {{ totalMarks }}
  </span>
</div>

Computed Properties vs Methods?

We could get the same result by using a method that outputs the total.

Instead of having the totalMarks function in the computed section, we can move it to the methods and in the view we can change the template to execute the method:

<span>
  Total marks are: {{ totalMarks() }}
</span>

While this gives the same output, we are taking a performance hit. Using this syntax, the totalMarks() method gets executed every time the page renders (ie: with every 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 results). By doing so, Vue can calculate the values only if the dependency changes. Otherwise, the previously cached values will be returned.

Because of this, 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. But, it’s also possible to have setters.

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

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

A Word on Watchers

While computed properties may be sufficient in most cases, watchers provide an additional level of control by allowing us to listen for changes to a property.

Watchers, as the name suggests, allows us to watch for changes in a model object. While it’s possible to use watchers to get the same results as computed values, it’s often more complex and expensive.

We can use watchers for more complex requirements, for example:

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

See on JSFiddle

✖ Clear

🕵 Search Results

🔎 Searching...