Introduction to Computed Properties in Vue JS

Learn why ‘computed properties’ are so vital for writing clean and efficient Vue code

Lotanna Nwose
Bits and Pieces

--

Photo by Michael Payne on Unsplash

Vue JS was created by Evan You and 234+ community lovers. It is a very progressive framework for building user interfaces. It consists of an approachable core library that focuses on the view layer only, and an ecosystem of supporting libraries that helps you tackle complexity in large Single-Page Applications. In this post, you will be introduced to ‘computed properties’, an exciting concept that will help you build mastery in Vue JS.

Tip: Share and reuse your Vue components to build apps faster as a team. Use tools like Bit (GitHub) to organize, share and reuse components across your apps. Give it a try.

Components with Bit: Easily share, use and develop anywhere

Before we start

This post is suited for intermediate frontend developers that use Vue JS, so being conversant with beginner concepts and installation processes is assumed. Here are a few prerequisites you should already have before you start to use Vue CLI 3 through this article.

You will need:

  • Node.js 10.x and above installed. You can verify if you do by running node -v in your terminal/command prompt.
  • The Node Package Manager 6.7 or above (NPM) also installed.
  • A code editor: Visual Studio Code is highly recommended. (here’s why)
  • Vue’s latest version installed globally on your machine.
  • Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:
npm uninstall -g vue-cli

then install the new one:

npm install -g @vue/cli

OR

  • Download a Vue starter project here
  • Unzip the downloaded project
  • Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:
npm install

What are computed properties?

Vue JS was built to be a view-layer-focused JavaScript framework. This is why it is template-based. However, in the course of writing code, developers can get carried away by the ease of use so much, that they begin to overpopulate their Vue templates with too much logic. Vue discourages this and advises breaking your application into components to enhance modular development. Inside each component though, the Vue team has gone an extra step to ensure that your templates are as simple and as presentable as possible, mainly by introducing ‘computed properties’.

It is best practice to use computed properties for complex logic computations, as putting your logic in the template can get real messy.

Why it is important

In Vue JS, computed properties create a platform for developers to have a kind of model-specific, complex values computed for the view. These values are usually bound to the selected dependency values and only update when there is a change in the bound element.

Computed properties syntax

<script>
export default {
computed: {

}

}
</script>

Methods and Computed Properties

Taking a look at the syntax, you will notice that it very much resembles the syntax of methods. They are really similar but Vue has built the computed properties in a way that makes them much better at complicated computations.

Demo: what you will build

You will build a simple Vue application with a Test component that will represent a Money game that shows basic mathematical expressions at work. If you have followed this post from the start, Open the Vue Canvas application in VS Code and copy the code below inside the Test.vue file:

<template>
<div>
<h2>The money Game</h2>
<p>Jack and Jill both won 2 all-access tickets to the Amusement Park </p>
<p>They both also have $100 each in their pockets and want to play the MG</p>
<button v-on:click="jack++">Add $1 to Jack</button>
<button v-on:click="jill++">Add $1 to Jill</button>
<p>Jack: ${{jack}}</p> <p>Jill: ${{jill}}</p>
<p>Jack's Total: {{addJack()}}</p>

<p>Jill's Total: {{addJill()}}</p>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
safe: 100,
jack: 0,
jill: 0
}
},
methods:{
addJack: function(){
console.log('Jack function ran!');
return '$'+(this.jack + this.safe);
},
addJill: function(){
console.log('Jill function ran!');
return '$'+(this.jill + this.safe);
}
}

}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
button {
background-color: rgb(58, 128, 194);
border: none;
color: white;
padding: 15px 32px;
margin: 5px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
}
</style>

Run the application in the editor’s terminal with the command below:

npm run serve

The application will look like this:

Demo App

This is the demo version with methods. Let us go ahead and see some of the problems with doing this computation at the method level.

The problem with methods

  1. Methods run from top to bottom, anytime any part of it is called. This is great but not reactive. Sometimes you want to have a collection of functions that only run when they need to. Computed properties are the reactive version of methods and do exactly that.
  2. Computed properties, due to their reactive manner, save these dependency values in a cache so that they can easily update it when the data property changes, without having to update everything top down.
  3. Methods by nature must be defined, referenced and finally called. This lifecycle is shortened with the computed properties as they are just defined and referenced, they never have to be called because Vue does the background work of watching them, in the cache, for changes.
  4. Optimal usage of your memory resources favors computed properties over methods. A typical example is in our demo above. We see that anytime we click on a button, both functions get executed. That is why we logged the statements in the console — to confirm these executions.

Solution: Computed properties

Following the syntax, you can see that computed properties are easy to write because they are essentially the same with methods. Change the script section in your Test.vue file to this to reflect them as computed properties:

<script>
export default {
name: 'Test',
data() {
return {
safe: 100,
jack: 0,
jill: 0
}
},
computed:{
addJack: function(){
console.log('Jack function ran!');
return '$'+(this.jack + this.safe);
},
addJill: function(){
console.log('Jill function ran!');
return '$'+(this.jill + this.safe);
}
}

}
</script>

That is all you have to do, now run the application again:

npm run serve

You should see this error message below as the application breaks.

It is very important to note that you have to go into your template and remove the function brackets that methods usually have. Your template section should look like this:

<template>
<div>
<h2>The money Game</h2>
<p>Jack and Jill both won 2 all-access tickets to the Amusement Park </p>
<p>They both also have $100 each in their pockets and want to play the MG</p>
<button v-on:click="jack++">Add $1 to Jack</button>
<button v-on:click="jill++">Add $1 to Jill</button>
<p>Jack: ${{jack}}</p> <p>Jill: ${{jill}}</p>
<p>Jack's Total: {{addJack}}</p>

<p>Jill's Total: {{addJill}}</p>
</div>
</template>

Both addJack() and addJill() method-calls, will become just addJack and addJill computed property references. Your application should now run without errors.

You see that the computed property only executes the needed functions, unlike the method. The full code to this tutorial can be found here on GitHub.

Conclusion

This article introduces you to the concept of computed properties in Vue JS and shows how it focuses on efficiency in handling complex computations and also being reactive at the same time. Do you use computed properties in your workflow? Let me know in the comments below!

Learn More

--

--

Helping Startups with Webhooks management at Convoy so they can focus on their core product offerings. Twitter:@viclotana