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.js 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 array of subjects defined in data-model:
<script>
export default{
  data:function{
     return {
       results: [
          {
          name: 'English',
          marks: 70
        },
        {
          name: 'Math',
          marks: 80
        },
        {
          name: 'History',
          marks: 90
        }
      ]
   }
 }
}
</script>

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.name}}: {{ 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.js remembers the values that the computed property is dependent on (ex: In the previous example, that would be results). By doing so, Vue.js 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.
<template>
    <input type="text" v-model="fullName"/>
    <h4>{{fullName}}</h4>
    <p>{{firstName}}</p>
    <p>{{lastName}}</P>
</template>

<script>
export default{
   data:function(){
       return{
           firstName:'Computed',
           lastName:'Property'
       }
   }
}
</script>
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.

 

 

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories