Skip to content

Difference between computed and methods in vue

  • by
Difference between computed and methods in vue

1. Overview

In this article, we will learn the difference between computed and methods in Vue js.

2. Computed properties in Vue

Computed properties allow you to separate complex in-template expressions from your template, thus helping in easier code maintenance. If you want to use an in-template expression more than once in your template, you can avoid repeating the expression again with help of computed properties.

For example, if we have an object with a nested array:

export default {
  data() {
    return {
      student: {
        subjects: [
          'English',
          'Science',
          'History'
        ]
      }
    }
  }
}

And we want to display different messages “yes” or “no” depending on student already has subjects or not:

<p>Assigned subjects:</p>
<span>{{ student.subjects.length > 0 ? 'Yes' : 'No' }}</span>

The template is getting cluttered because of the complex in-template expression.

That’s why for complex logic that includes reactive data, Vue recommends using a computed property.

Here’s the same example, refactored:

export default {
  data() {
    return {
      student: {
        subjects: [
          'English',
          'Science',
          'History'
        ]
      }
    }
  },
  computed: {

    isSubjectAssigned() {

      return this.student.subjects.length > 0 ? 'Yes' : 'No'
    }
  }
}
Computed properties
Computed properties

3. Difference between computed properties and methods in Vue

You may have noticed we can achieve the same result by invoking a method in the expression:

The two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. 

A computed property will only re-evaluate when some of its reactive dependencies have changed.

This means as long as student.subjects has not changed, multiple access to isSubjectAssigned computed property will immediately return the previously computed result without having to run the getter function again.

This also means the following computed property will never update after initial computation, because Date.now() is not a reactive dependency:

Computed property never changes as Date.now is not reactive

However, a method invocation will always run the function whenever a re-render happens.

A computed property is helpful when you want to perform a lot of expensive computations. Once computed, Vue reuses the computed value. It performs the computation only when the underlying reactive property that it depends on changes, in this case, student.subjects reactive data property.

4. Conclusion

To sum up, we have learned the difference between computed property and methods in Vue js.

Leave a Reply

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