Vue.js (cli3) : Difference between calculated properties and observers (Part. 6 of tutorial) ✅ 2019 | EN/FR

Thibault Jp
Vue.js Developers
Published in
5 min readAug 20, 2019

Part. 6 : Difference between calculated properties and observers(Computed/Watch) ⌚️

👊 If you have not read part 5 she is here

🚁FR: version française disponible ici

In this part we will see a very important notion in Vue.js, to be precise it is even 2 notions (which is a bit alike, and that it is difficult to differentiate if we learn poorly their use): these are the calculated properties as well as observers

Let’s start with the calculated properties

As we have seen in a previous part, it is possible to use the values of our component (data) in the <template> of our component with the extension.

This method works but it is only viable when our business logic (ie the various operations performed on this variable) are minimal. Like inverting a string, put it in uppercase, concatenate a string with another..etc.

From the moment it gets more complicated (like cutting a string, performing date conversions, processing the data from an API and filtering it through filter) and it’s necessary to think a bit to understand what the variable can display is that you need a computed property

The calculated property is presented in the same way in our template, a small example of a call:

For a simple property:

<template>
<div>
<p> Message : {{ msg }} </p>
</div>
</template>

For a calculated property:

<template>
<div>
<p> Message avec propriété calculée: {{ msgCalcule }} </p>
</div>
</template>

The real question is, how does it work?
First let’s make a quick reminder about the structure of our vue component

As we have seen in a previous part, Vue.js provides “hooks” to perform actions on the life cycle of the application. For the moment we will not go into details, but know that these elements, like the functions as well as the calculated properties are declared at the same level as you can see on the screenshot above

If you are observant, the computed properties are in this example, it is the computed

Let’s start by declaring our first computed

In this example, we declare a computed named “onlyFirstWord” which as its name implies is responsible for returning only the first word of our msg variable (by capitalizing this word)

It is therefore very easy to use it now thanks to the accessor this of our component (which corresponds not to the instance of view, but to the instance of the component)
If we were in the class where we declare our instance of vue:

const vm = new Vue ({
data: {
msg: "hello world"
}
})

At this point the computed (if it was declared) would be accessible via vm.onlyFirstWord

Let’s use it in our template:

For that it is a little different, as for the data, it is not necessary to use this, you can directly pass the name of the computed in the whiskers like this:

The real question: Will we have done a method in “methods” that would have given the same result? The answer is yes. But no .. I explain myself

The interest of Computed is that it is cached. Its properties are however “re-evaluated” if one of the dependencies changes. That is to say, that for example, in our test below, if the variable “msg” is modified, the computed will be re-evaluated and will thus be modified. If we had used “methods” no matter how many “msg” changes, our method would never have been modified

A very telling example and that I use his times a lot is:

  • We have a computed A to do a forEach on a table of 100 elements (strings) to keep only what interests him (the one that does not include space for example.
  • We have a computed B which is based on the computed A for example to add to each element a dynamic ID following our chain

The interest here in using computed is that their properties are cached. Which allows to carry out heavy treatments without having to recalculate every time
But if you do not want this feature: Choose methods

The observers

When you read “observer” you probably think that it is already what we do: Check that data to change to perform a refresh with computed. In fact it’s more complicated than that. Vue provides a more general way to observe a data change on an instance. This is called the “watch” property

The big difference is that unlike a computed which returns a value directly after a modification. Watch allows you to edit a specific value. Let’s take a stupid example:

data() {
return {
hello : "Hello",
word : "Word",
fullText: "Hello Word",
}
},watch:{
hello: function (value) {
this.fullText= value + ' ' + word
},
word: function (value) {
this.fullText = this.hello + ' ' + value
}

Which is very good in itself, but for example in this case (as in a lot of cases actually ..) a computed is more than enough and faster to implement I find:

data() {
return {
hello : "Hello",
word : "Word",
fullText: "Hello Word",
}
},
computed: {
fullText () {
return this.hello + ' ' + this.word
}
}

Be aware that it is also possible to pass parameters to a Computed using a function, it is not a method that I find very pretty, but it is quite practical in some cases when one is blocked

<script>
export default {
data
() {
return {
hello : "Hello"
word: "Word"
}
},
computed: {
longText() {
return function fulltext(mot) {
return this.hello + ' ' + mot
}
}
}
}
</script><template>
<div>
<p> {{ longText(word) }} </p>
</div>
</template>

The most practical in any case is to go through what we call Mutators you probably have already heard, it is the GETTER and SETTER (to “get” and “define”)

computed: {
fullText: {
// GETTER
get: function () {
return this.hello + ' ' + this.word }// SETTER
set
: function (newValue) {
const newHelloWord= newValue.split(' ' )
this.hello= newHelloWord[0]
this.word= newHelloWord[newHelloWord.length — 1]
}
}
}

This example is a bit like the official documentation from Vue.js

We see here the simple way Getter recover our computedcomme we have already done previously. And in the Setter one can see how it is possible by passing a word in parameter of the computed to modify this one by using for example the syntax:

this.fullText = "Premier mot"

Thank you for reading this tutorial! ❤️

You can find the different parts of my “big tutorial” on Vue.js on my profile here

Feel free to contact me on LinkedIn or by email at: thibault.jeanpierre.dev@gmail.com in case of problems.

Next part come soon 😃

--

--

Thibault Jp
Vue.js Developers

Front-End Developer - UX-UI Designer — Amiens FRANCE