Using computed in VueJS & The difference between computed and methods

Using computed in VueJS & The difference between computed and methods

Zill Nguyen
Zill Nguyen

What is computed? and How to use it!

Computed or Computed property is the place to process data on Vue.js, the data is processed from the properties returned in the data or a certain binding property. Because of taking data in data, computed does not accept any parameters and is required to return a value. I will use an example like the one on vuejs.org to explain it to you. For example, if we have an object with a nested array:

export default {
  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  }
}


And I want to show different messages depending on whether the author already has the books or not:

<p>Has published books:</p>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>

This makes our template look untidy, it takes time to read and understand and realize the above code will display messages in reverse order.

export default {
  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  },
  computed: {
    // a computed getter
    publishedBooksMessage() {
      // `this` points to the component instance
      return this.author.books.length > 0 ? 'Yes' : 'No'
    }
  }
}
<p>Has published books:</p>
<span>{{ publishedBooksMessage }}</span>

In the above example, the Computed property is always responsive in Vue.js, every time the input data is changed it will automatically update the value. The best part here is that we can create relationships between dependencies: computed getter functions have no side effects, making them easy to understand and test.

The difference between computed and methods

Some of the differences between computed and methods:

  • When calling computed we can't add a pair of commas () after it, that means computed can't take input parameters like methods.
  • Because it does not take input parameters, computed should only be used with data available in the component's data.
  • Computed will only recalculate every time its dependent variables change, and methods will be computed whenever it is called, so if you know how to take advantage of computed to calculate available data, it will improve. performance of your app. The great thing about computed is that it will be cached so let's say you have a computed with a bunch of computations, lots of loops in it, that if the dependent variables don't change then using it will only be computed once, the next time the results will be reused from the previous time.