VueJS

How to Use Computed Properties in VueJS

What is Computed Properties in VueJS?

Computed properties in vuejs is the replacement of inline logic on template, we often use to write simple operation, filters on template it self, but for live project it’s hard to maintain such kind of logic on templates, so vuejs provides a better way to replace doing inline coding by using computed properties.

In last tutorial How to Handle Events in VueJS 2.0 I have given details on how to use events in vuejs and to demonstrate event handling I have given a simple example by creating to do list application, I am going to use same example here to explain the use of computed properties, if you have’t read the tutorials do visit and a to take a look on to do list example.

Before going to follow real time example first let’s take a look at use and the basic syntax of vuejs

How to Use Computed Properties in VueJS?

Here we are going to use simple example to get understand the syntax of vuejs computed properties:

Let’s say we an name and we want to display it revers we can do that in following way:

Example Without using Computed Properties:

<!DOCTYPE html>
<html>
<head>
    <title>VueJS 2.0 Computed Properties</title>
</head>
<body>

<div id="app">
     {{ name.split('').reverse().join('')}}
</div>
<script src="https://unpkg.com/vue@2.3.4"></script>

<script>

    var app = new Vue({
        el: "#app",
        data: {
           name: 'Yogesh'
        }
    });

</script>
</body>
</html>

Output: hsegoY

So in the above example we are simply using the name and converting into array next by using reverse method we simply doing reverse of the array elements and join it again to string by using job method, to the reason to giving details on logic is we are writing little more complicated logic on template, let’s replace by using computed properties:

Example using Computed Properties:

<!DOCTYPE html>
<html>
<head>
    <title>VueJS 2.0 Computed Properties</title>
</head>
<body>

<div id="app">
     {{ reverseName }}
</div>
<script src="https://unpkg.com/vue@2.3.4"></script>

<script>

    var app = new Vue({
        el: "#app",
        data: {
           name: 'Yogesh'
        },
        computed: {
            reverseName: function()
            {
                return this.name.split('').reverse().join('')
            }
        }
    });

</script>
</body>
</html>

Output: hsegoY

The output is same for both the examples but the way we are adding our logic is different and it makes to use write javascript in side the script instead of writing it on template.

Real time to do list Example using Computed Properties:

In the following example we have array of tasks and we going to filter those using computed properties, meaning will filter in-completed and completed tasks.

<!DOCTYPE html>
<html>
<head>
    <title>VueJS 2.0 Computed Properties</title>
</head>
<body>

<div id="app">
    <input type="text" v-model="task" placeholder="Enter Task">
    <button v-on:click="addTask">Add Task</button>
    <br><br>

    <h2>Tasks ({{ inCompleteTasks.length }})</h2>
    <table v-if="inCompleteTasks.length > 0">
        <tr>
            <th width="10">No.</th>
            <th>Task</th>
            <th>Mark as Completed</th>
            <th>Remove</th>
        </tr>
        <tr v-for="(task, index) in inCompleteTasks">
            <td>
                {{ index + 1 }}
            </td>
            <td>
                {{ task.name }}
            </td>
            <td>
                <button v-on:click="taskCompleted(task)" >Completed</button>
            </td>
            <td>
                <button v-on:click="removeTask(task)" >X</button>
            </td>
        </tr>
    </table>
    <h2>Completed ({{ completedTasks.length }})</h2>
    <table v-if="completedTasks.length > 0">
        <tr>
            <th width="10">No.</th>
            <th>Task</th>
        </tr>
        <tr v-for="(task, index) in completedTasks">
            <td>
                {{ index + 1 }}
            </td>
            <td>
                {{ task.name }}
            </td>
        </tr>
    </table>
</div>
<script src="https://unpkg.com/vue@2.3.4"></script>

<script>

    var app = new Vue({
        el: "#app",
        data: {
            task: '',
            tasks: [
                {name: 'Task 1', is_completed: true},
                {name: 'Task 2', is_completed: true},
                {name: 'Task 3', is_completed: true},
                {name: 'Task 4', is_completed: false},
                {name: 'Task 5', is_completed: false},
                {name: 'Task 6', is_completed: false},
                {name: 'Task 7', is_completed: false},
                {name: 'Task 8', is_completed: false},
            ]
        },
        computed: {
            completedTasks: function () {
                return this.tasks.filter(function (task) {
                    return task.is_completed == true;
                });
            },
            inCompleteTasks: function () {
                return this.tasks.filter(function (task) {
                    return task.is_completed == false;
                });
            }
        },
        methods: {
            addTask: function () {
                if (this.task != '') {
                    this.tasks.push({name: this.task, is_completed: false});
                    this.task = null;
                }
            },
            removeTask: function (task) {
                var index = this.tasks.indexOf(task);
                this.tasks.splice(index, 1);
            },
            taskCompleted: function (task) {
                task.is_completed = true;
            }
        }
    });

</script>
</body>
</html>

If you take a look in details you will get to know you can use computed properties in real time web applications.

You can checkout the live example of todo list application of above script to see how above script works:  To Do List Live Example Using VueJS Computed Properties

Conclusion:

So in this tutorial we have learn following points:

  1. What is VueJS Computed Properties
  2. How to use Computed properties
  3. How to create to do list application using computed properties.
  4. Filter Array Object using Computed properties

Get Notified when new stuff is available

More intermediate and advanced stuff is coming soon, I will update you when we get new stuff updated hear you can subscribe to get notified whenever we update new tutorial.

Make sure to confirm your email address by clicking on activation link from the verification email to complete subscription.

Stay Tuned.

Happy Learning!

Yogesh Koli

Software engineer & Blogger live in India, has 8+ years of experience working with the Front-end and Back-end Web Application Development.

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example…

2 years ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify…

2 years ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter…

2 years ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the…

2 years ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them,…

2 years ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super…

2 years ago