Main Difference Between Method and Computed Property in Vue.js

In Vue.js, both methods and computed properties are used to define dynamic behavior in your Vue components, but they serve different purposes and have different behaviors.

Methods in Vue.js

  • Methods in Vue.js are plain JavaScript functions defined within the methods object of a Vue component.
  • They are called when invoked in response to some event, such as a click event, or when explicitly called from within the component.
  • Methods are useful for handling events, performing calculations, or executing complex logic.
  • Methods are re-evaluated on each render, regardless of whether their dependencies have changed or not.
    // Vue component with a method
    Vue.component('my-component', {
      data() {
        return {
          count: 0
        };
      },
      methods: {
        increment() {
          this.count++;
        }
      }
    });
    

Computed Properties in Vue.js

  • Computed properties are functions defined within the computed object of a Vue component.
  • They are similar to methods in that they compute a value, but they are cached based on their dependencies.
  • Computed properties are only re-evaluated when their dependencies change. This means if the dependent data hasn't changed, Vue will return the previously computed result, which can improve performance.
  • Computed properties are great for performing data manipulation or filtering.
    // Vue component with a computed property
    Vue.component('my-component', {
      data() {
        return {
          items: [1, 2, 3, 4, 5]
        };
      },
      computed: {
        itemCount() {
          return this.items.length;
        }
      }
    });
    

Summary

Methods are called when explicitly invoked or in response to events, and they are re-evaluated on each render. Computed properties, on the other hand, are cached based on their dependencies and are only re-evaluated when those dependencies change. Use methods for operations that need to be explicitly invoked or for handling events, and use computed properties for derived data that depends on reactive data.