Header Ads

Learn Vue.js Step By Step: Computed Properties and Watchers


In our last lesson in this series we've learned about dynamic styles and classes. In this lesson we will be talking about computed properties and watchers.

Vue.js allows you in-template expressions like so:
<!DOCTYPE html>
<html>
<head>
<title>Learn Vue.js Step By Step: Computed Properties and Watchers</title>
</head>
<body>
    <div id="app">
        {{ message.split('').reverse().join('') }}
    </div>

    <script src="https://unpkg.com/vue"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: 'Hello World'
            }
        })
    </script>
</body>
</html>
Sure this will work, but imagine if you a have lot of expressions like this in your template. This will make your template very difficult to maintain. When you are in the situation where you ended putting complex logic to your template that is a good indication that you need to use computed properties.

Now, let's take a look what will our previous example will look like using computed properties:
...
    <div id="app">
        Original Message: {{ message }}

        Coumputed Reversed Message: {{ reversedMessage }}
    </div>

    <script src="https://unpkg.com/vue"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: 'Hello World'
            },
            computed: {
                reversedMessage() {
                    return this.message.split('').reverse().join('');
                }
            }
        })
    </script>
...
As you notice all your computed properties should be inside the Vue computed property. Also, computed properties are reactive and cached based on their dependencies. So, if the value of message property is updated the reversedMessage will be automatically updated too.

The result of the above code should look like this:
Original Message: Hello World 
Coumputed Reversed Message: dlroW olleH

Watchers

Vue also provides a generic way to react to data changes using watch. This is usually useful when you want to perform asynchronous or expensive operations in response to changing data:
...
<div id="app">
    <input type="text" v-model="q" />
    <div v-if="searching">Searching...</div>
    <div v-if="! searching && q">
    Suggestions:
    <ul>
        <li v-for="suggestion in suggestions">{{ suggestion.name }}</li>
    </ul>
    </div>
</div>

<script src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            q: '',
            suggestions: [],
            searching: false,
        },
        watch: {
            q() {
                this.searching = true;
                this.getSuggestions();
            }
        },
        methods: {
            getSuggestions() {
                setTimeout(function () {
                    this.suggestions = [
                        {name: 'Jane Doe'},
                        {name: 'John Doe'}
                    ];
                    this.searching = false;
                }.bind(this), 1000);
            }
        }
    })
</script>
...
Notice we're just simulating here the suggestions, but most probably it will coming from an ajax request but you get the idea.

That's all for this lesson, for more information about computed properties and watchers you can refer to the official documentation. As always if you have any questions please don't hesitate to write it down in the comment below and see you in the next lesson. Thanks!

Previous: Dynamic Styles and ClassesNext: Components


No comments