In Vue.js, both methods vs computed properties can return values for use in your templates, but they work differently behind the scenes. Computed properties are reactive and cached based on dependencies, while methods run every time they’re called.

Knowing when to use each helps you write efficient, performant components.

What Are Methods in Vue?

A method is just a function defined in the methods option (or inside <script setup> using setup() or defineExpose). Methods run every time they’re called in the template or in your logic.

Example:

<template>  <p>{{ greet() }}</p>

</template>

 

<script setup>

function greet() {

  return ‘eSparkBiz!’

}

</script>

Every time Vue re-renders the component, the method runs each time it’s called.

What Are Computed Properties?

A computed property is a special, reactive getter that caches its result until its dependencies change. Vue recalculates it only if its reactive data sources update.

Example:

<template>  <p>{{ fullName }}</p>

</template>

 

<script setup>

import { ref, computed } from ‘vue’

 

const firstName = ref(‘Jane’)

const lastName = ref(‘Doe’)

 

const fullName = computed(() => `${firstName.value} ${lastName.value}`)

</script>

Here, fullName only recalculates if firstName or lastName changes.

Also Read: Top VueJS Interview Questions to Ask Before Hiring a Vue.js Developer

Key Differences Between Methods and Computed Properties in Vue.js

Learn the key differences between Vue.js methods and computed properties to write efficient, reactive, and maintainable components.

Feature

Methods

Computed Properties

Caching No caching Cached until dependencies change
When It Runs Runs on every re-render Runs only when dependencies update
Arguments Can accept arguments Cannot accept arguments
Use Case For actions & fresh results For derived, reactive values
Template Use Called like a function Used like a variable

Also Read: Best Way to Declare Global Variables in Vue.js

Key Takeaway

The main difference between Vue methods and computed properties is caching. Use computed properties for values derived from reactive data that need to be efficiently cached and re-evaluated only when dependencies change. 

Use methods for event handling, side effects, or any logic that needs to run every time it’s called, potentially with arguments.

Related Resources