2

When using Vue.js, when should you use a method or a computed property setter? There seems to be little distinction in the documentation, or numerous articles. Usually articles present computed property setters as little more than a footnote.

Given that both methods and setters accept parameters, is there a particular reason you'd use one or the other? As far as I can see methods would be all you need.

Edit:

This is literally not a repost because the linked SO answer contains the word setter once and only in vague passing:

computed properties are converted into a property of the Vue with a getter and sometimes a setter.

Great, so how does this elaborate on the subject of this post, when to use a SETTER vs a method?

tony19
  • 125,647
  • 18
  • 229
  • 307
user9993
  • 5,833
  • 11
  • 56
  • 117
  • Is there question about computed properties vs methods? Because that has been covered several times already – samayo Dec 05 '17 at 14:42
  • None of the them discuss my title. – user9993 Dec 05 '17 at 14:43
  • Alright I'll re-open it. I think your confusion stems from a misunderstanding of what a setter actually is, which is only *part* of a property. A setter doesn't accept parameters, it accepts a single value. You don't "call" a computed property you set it; `this.myComputed = "some value"`, which in turn funnels the value through the defined setter. Most any discussion you will find about properties vs methods in any other language (c# in several SO discussions) apply as well. In Vue, I typically only use a setter when I want to use a computed property in a `v-model` expression. – Bert Dec 05 '17 at 15:51

2 Answers2

1

Computed properties are cached so they can benefit you when it comes to performance. They do not work like methods, as they do not accept arguments.

I use them mostly to modify existing data or make it easier to access nested data.

The part about caching is something that can end up being a hassle. They will always cache unless their direct dependencies change. Properties within computed properties that are within controls blocks will usually not update the computed property(not seen as a direct dependency).

This is something you need to be aware of.

When using things like large v-for lists you will want to to take advantage of the caching ability of computed properties since unlike with a method you won't have to perform the logic inside of it over and over, unless the direct dependencies of the computed property change.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
0

Computed properties should be used to display data relative to existing data. While methods should be used to do an action and/or change data.

Maxim
  • 5
  • 2