DEV Community

Ayu Adiati
Ayu Adiati

Posted on

Methods vs Computed in Vue

Hello πŸ‘‹πŸΌ,

Lately I've been learning Vue.
So today I learned about computed property.

In my understanding (please correct me if I'm wrong), computed is the same as methods property, only it will be re-executed if data that are used within the property are changed.
While methods property will be re-executed for any data changes within the page.

In which condition is the best practice to use methods or computed?

Thank you in advance for any help 😊

Oldest comments (8)

Collapse
 
drewclem profile image
Drew Clements

Another way to look at computed is that they can be used as dynamic data for every render.

Methods are functions that can be called as normal JS functions, but computed properties will be β€œre-calculated” anytime some data changes in the component.

Collapse
 
adiatiayu profile image
Ayu Adiati

Thanks, Drew!

So computed is more like a method to update data to be dynamic?

When would we want to use methods or computed?

Collapse
 
drewclem profile image
Drew Clements

Exactly!

Another important thing to note is that computed properties are available the same as properties in your data store

So

data() {
  return {
    number: 1
  }
}
Enter fullscreen mode Exit fullscreen mode

is the same as

computed: {
  number() {
    return 1
  }
}
Enter fullscreen mode Exit fullscreen mode

Both would be available with using this.number or {{ number }}

But, if you ever needed number to update based on something else in the component, then the computed would do it auto-magically.

Thread Thread
 
adiatiayu profile image
Ayu Adiati

Thank you, Drew!!! πŸ˜ƒ

Collapse
 
sebrax profile image
Sulivan Braga

It’s already answered but to mention, you cannot send params on computed.

Collapse
 
adiatiayu profile image
Ayu Adiati

Good to know this!
Thank you, Sulivan πŸ˜ƒ

Collapse
 
aat profile image
Aashutosh Anand Tiwari

I think we can

Collapse
 
tpoisson805 profile image
Tim Poisson

Also should mention that Computed Properties are automatically cached while Methods are not.

If you are running an 'expensive' operation, it is best to cache this data as a Computed Property or else the function will re-run everytime the page refreshes which creates unnecessary overhead.

For larger applications Computed Properties are typically used in conjunction with Vuex to help access global application data as well.