Methods vs Computed Properties in Vue.js: Understanding the Differences

In Vue.js, both methods and computed properties are used to return values and perform operations. However, they serve different purposes and have distinct behaviors. In this article, we’ll explore their differences and when to use each one effectively.

1. Methods (methods)

Methods in Vue.js are functions that execute every time they are called. They do not cache results and always run fresh when invoked.

Key Characteristics of Methods

  • Runs each time it is called.
  • Does not cache results.
  • Best suited for event handling or performing actions on demand.

Example: Using a method to calculate the sum

<script setup>
import { ref } from 'vue';

const num1 = ref(5);
const num2 = ref(10);

const sum = () => {
  console.log('Method is called');
  return num1.value + num2.value;
};
</script>

<template>
  <p>Sum: {{ sum() }}</p>
</template>

Here, sum() is a method, and it executes every time the template renders.

2. Computed Properties (computed)

Computed properties are reactive and automatically update when their dependencies change. They also cache their results, preventing unnecessary re-execution.

Key Characteristics of Computed Properties

  • Only recalculates when dependencies change.
  • Caches the result to optimize performance.
  • Ideal for derived state (e.g., filtering, formatting, calculations).

Example: Using a computed property for sum calculation

<script setup>
import { ref, computed } from 'vue';

const num1 = ref(5);
const num2 = ref(10);

const sum = computed(() => {
  console.log('Computed property is called');
  return num1.value + num2.value;
});
</script>

<template>
  <p>Sum: {{ sum }}</p>
</template>

Here, the computed property sum only recalculates when num1 or num2 changes, making it more efficient than a method.

Leave a comment

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