Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

VueJS Computed Properties

Computed properties are methods that behave like properties. They are useful when you want to perform some complex logic on the property(s) before you can return its value. For example, you may have a property that contains a string that you may want to reverse then capitalize and display to the user.

You can use JavaScript Expressions directly when outputting the result but that puts business logic in your templates and ideally we should just output data in templates and not perform complex business logic. This lesson will teach you how and when to use computed properties.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - this is mainly needed for development purposes only. You need NPM which comes with Node to work with tools like Vue CLI
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.
  • HTML & CSS Basics - this is an added advantage. Vue works on the HTML elements to manipulate them. The styling is done using CSS so you must be familiar with the basics

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called vue-components

Open the directory vue-components in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this is the file that will contain our application source code

The following visualizes our project setup

vue-components
-index.html

How Computed Properties Work

Computed properties are defined in the same way that we define functions and they should return a value. Computed functions use and are dependent on regular properties. Once a computed property has been executed once, the result is cached and next time that the property is accessed, it is not executed again but simply returns the previous result.

If the value of the property that the computed property depends on changes, then the computed property is called automatically, the cache result updated and re-rendered in the Virtual DOM where the property is used.

Computed Property Example

Let's now look at a practical example. We will create a simple application that has two member variables first_name and last_name then we will display the full name. We will look at three ways of doing this and then decide which is the best way of doing it.

Open the file index.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>VueJS Computed Properties</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Full name: {{first_name}} {{last_name}}</p>
            <p>Full name (Method): {{fullName()}}</p>
            <p>Full name (Computed): {{full_name}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    first_name : 'John',
                    last_name: 'Doe'
                },
                methods: {
                    fullName: function(){
                        console.log('Getting customer name from method');
                        return this.first_name + ' ' + this.last_name;
                    }
                },
                computed: {
                    full_name: function(){
                        console.log('Getting customer name from computed');
                        return this.first_name + ' ' + this.last_name;
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • first_name : 'John',last_name: 'Doe' defines two data members first_name and last_name and assigns them default values.
  • methods: {...} defines a normal Vue function fullName that simply returns the combination of the first_name and last_name separated by a space. We are also logging a message in the console whenever the method is executed. The reason for this will become clear as we proceed
  • computed: {...} defined a computed property full_name that returns the full name using the same logic as the function in the methods parameter.
  • <p>Full name: {{first_name}} {{last_name}}</p> displays the value of our variables to create a full name. This works but looks weird and you cannot immediately tell that the purpose of this is to create a full name. These are some of the disadvantages of this approach.
  • <p>Full name (Method): {{fullName()}}</p> we are calling the function to display the full name. This methods is much better than the first one because it explicitly communicates its intent which is to display the full name. Anyone reading the code will know immediately what's on. The major draw back of this approach is that every time that the application renders the Virtual DOM, the code in the method is executed. For our simple example its ok but when you have huge data performing API operations that can slow down things. The minor draw back is the fullName() looks unnatural compared to say full_name as a property and not a method
  • <p>Full name (Computed): {{full_name}}</p> displays the value of the computed property full_name like its just any ordinary property. The intent is communicated and it has a natural look to it. In this case, using a computed property makes more sense.

Open the file index.html in the web browser

You should be able to get the following results

Full name: John Doe
Full name (Method): John Doe
Full name (Computed): John Doe

Let's now look at the power of computed properties when compared to normal methods. Open the developer tools section in the browser and open the console.

Run the following command in the browser

vm.first_name = 'Rodrick'

The name in the page should change from John Doe to Rodrick Doe

You should also be able to get the following messages in the console terminal

Getting customer name from method
Getting customer name from computed

Nothing special so far. Let's now call the method directly from the terminal. We will call the terminal more than once to prove a point.

Run the following command in the browser console

vm.fullName()

You should be able to get the following result

{{image place holder}}

Getting customer name from method
"Rodrick Doe"

Repeat running the command several times and you will get the same result including the console message always. This is because every time you call a function, the code is executed.

Let's now look at how computed properties differ from functions

Run the following command in the console

vm.first_name

You should be able to get the following result

"Rodrick"

Notice the message Getting customer name from computed has not been displayed. This is because the code in the computed property is not been executed. We are getting the result that has been stored in the cache. This is a huge performance gain because our property depends on first_name and last_name but these have not been updated so we don't have to execute the code in the computed property function definition.

Let's now change the value of first_name to Jane like so

vm.first_name = 'Jane'

You should be able to get the following results

{{image place holder}}

Getting customer name from method
Getting customer name from computed

Notice how the code in the computed property method was automatically executed when one of the properties that our computed property depends on was updated. The result is then stored in the cache again and it will not be executed until one of the values for the dependents changes.

The code in the method was not executed as evidenced by the lack of the console message in the results. The code in the method has to be executed explicitly it is not done automatically like in computed properties.

Computed Property Getters and Setters

Computed properties also support the concept of getters and setters. Getter is a function that is used to return a value to a property while setter is a function that is used to assign a value to a property. The advantages of using getters and setters is we can add business logic before performing any operations on the property. For example, you can validate the value to be assigned to a property in a setter function before assigning it.

Open the file getset.html and add the following code to it

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>VueJS Computed Property Getter Setter</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Username: {{username}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    name : 'John'
                },
                computed: {
                    username: {
                        get: function(){
                            return '@' + this.name;
                        },
                        set: function(value){
                            this.name = value.toLowerCase();
                        }
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • username: {...} defines a computed property as an object that has two functions in it set and get. The get method simply appends the symbol @ to the variable name then returns the result as the username. The method set receives a parameter value that it converts to lower case letters then assigns the result to the variable name.

Open the file getset.html in the browser

You should be able to get the following results

Username: @john

Open the developers tools and run the following console command

vm.username = 'RICK'

The above code assigns the value RICK to the variable name in upper case letters. Our setter function converts the received value to all lower case letters so the username in the browser will be displayed as follows

Username: @rick

Summary

Computed properties are properties that are defined like functions but used as regular properties. The return result from computed properties is cached until one of the properties that it depends on is updated. Get and set methods can be used on computed properties to add business logic to the value been returned or validation rules to the value to be assigned before that is done. Computed property methods are only executed when dependent values change while regular methods are always executed whenever the function is called.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

VueJS Templates

VueJS Watched Property

Leave A Reply