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 ๐
Top comments (8)
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.
Thanks, Drew!
So computed is more like a method to update data to be dynamic?
When would we want to use methods or computed?
Exactly!
Another important thing to note is that computed properties are available the same as properties in your data store
So
is the same as
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.
Thank you, Drew!!! ๐
Itโs already answered but to mention, you cannot send params on computed.
Good to know this!
Thank you, Sulivan ๐
I think we can
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.