Ali Soueidan

Ali Soueidan Front-End Developer

👋 Hello, I am Ali, a Developer based in Hamburg/Germany, and this is my Blog.

Computed Properties (Vue basics)

I vue we have many options to deal with data visualizing it for the user. One way is to use Computed Properties as one of the basic concepts of Vue. What is the difference between usual Data and Computed Properties, as well as when and how to use them is (quick and dirty) explained in this article.

What are Computed Properties

Computed Properties can be seen as of an combination on the methods option and the data function in Vue – to be more precise they contain and execute functionality as like methods and return data as like the data function. Computed Properties are always return sometging and are by default read only, so they do not change data.

Why do we need Computed Properties

As mentioned earlier, Computed Properties are a bit like Methods, so why do we need them at all? Unlike Methods, Computed Properties are only called when a dependecy changes, whereas a Methods are called whenever the View is rerendered – Computed Properties are cached based on their dependecies. Of course it is more performant to call a function only if something changed, that the function is related to, so using Computed Properties instead of Methods results in better performance. So whenever we want to change the presentation of existing data, we would prefer a Computed Property, instead of the functions of the Methods-Option, if we want to change data instead, we should go for Functionallity of the Methods-Option.

Computed Properties and setters

In the last section, I pointed out that we don’t want to change any data with Computed Properties! So far this is correct – by default Computed Properties are getter only methods – however – we can also assign a setter to computed properties if we need it.

But why do we have a setter function in our computed, if we don’t want to change any data with it? At this point, I would like to look at the code example above, in which as well a getter and a setter are in usw. Let’s assume we have two inputs, one for changing firstName and one for LastName. Changes are recognized by our computed property „computedFullname“ and accordingly the output will be changed – let’s assume that we output computedFullname in a third input. In this case computedFullname would change in this input whenever e.g. by user input firstName or lastName would be changed – but if we would change computedFullname in its input, this would have no effect on firstName or lastName and therefore computedFullname can be called with a setter, which if computedFullname changes this can be passed to firstName and/or lastName – for this we use a setter – this is exactly what we do in the code example above and for this (and only for this) we use a computed property instead of a method to change the data.