0
0
Vueframework~5 mins

Computed vs method performance in Vue

Choose your learning style9 modes available
Introduction

Computed properties and methods both help show data in Vue. But computed properties remember their result until data changes, making them faster for repeated use.

When you want to show a value that depends on other data and updates automatically.
When you need to avoid repeating heavy calculations every time the page updates.
When you want to run a function only when its input data changes.
When you want a simple way to keep your template clean and reactive.
Syntax
Vue
export default {
  data() {
    return {
      number: 5
    };
  },
  computed: {
    squared() {
      return this.number * this.number;
    }
  },
  methods: {
    squaredMethod() {
      return this.number * this.number;
    }
  }
};

Computed properties are defined inside the computed object.

Methods are defined inside the methods object and run every time they are called.

Examples
This computed property doubles the value and caches the result until value changes.
Vue
computed: {
  doubled() {
    return this.value * 2;
  }
}
This method doubles the value but runs fresh every time it is called, even if value did not change.
Vue
methods: {
  doubledMethod() {
    return this.value * 2;
  }
}
Sample Program

This Vue component shows a number and its square calculated two ways: with a computed property and a method. Clicking the button increases the number.

Open your browser console to see when each calculation runs. The computed property runs only when the number changes. The method runs every time the template updates.

Vue
<template>
  <div>
    <p>Number: {{ number }}</p>
    <p>Computed squared: {{ squared }}</p>
    <p>Method squared: {{ squaredMethod() }}</p>
    <button @click="increment">Increase Number</button>
  </div>
</template>

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

const number = ref(5);

function increment() {
  number.value++;
}

const squared = computed(() => {
  console.log('Computed runs');
  return number.value * number.value;
});

function squaredMethod() {
  console.log('Method runs');
  return number.value * number.value;
}
</script>
OutputSuccess
Important Notes

Computed properties cache their results and only update when their dependencies change.

Methods run fresh every time they are called, which can slow down your app if used for heavy calculations.

Use computed properties for values that depend on reactive data and need to update efficiently.

Summary

Computed properties are faster because they remember results until data changes.

Methods run every time and do not cache results.

Choose computed properties for reactive, dependent values to improve performance.