VueJS: Computed Functions

in VueJS Basics

In a previous tutorial we learnt how you can add a message to the page in VueJS by using the handlebars syntax.

{{ message }}

Along with simply outputting data properties on the page you can also add additional logic to the template files when outputting the message, for example if you want to make the message all uppercase you can do this in the template.

{{ message.toUpperCase() }}

This works fine if you only need to do this in one place on your template, the problem comes when you need to do this functionality in multiple places on your template as you'll need to remember to add the .toUpperCase() function on all messages.

This is where VueJS computed property can be so useful, think of them like static methods you can call from within the template. Instead of having {{ message.toUpperCase() }} in the template you can replace it with {{ uppercaseMessage }}. Then in your Vue object we can create a computed function of uppercaseMessage that will get the message data property and return the value in uppercase.

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Display This'
        },
        computed: {
            uppercaseMessage: function()
            {
                return this.message.toUpperCase();
            }
        }
    })
</script>

You can now open your console in your browser can change the default message value by going app.message = 'changed' when you hit enter you'll also see that the uppercase value is automatically changed.

You can achieve the exact same result by using VueJS methods, the difference between methods and computed functions is that computed functions are cached. Therefore if your method is a bit more confusing caching can become more important. This means once the value of message is changed the value of computed.uppercaeMessage is cached so if this is used on multiple places the template it will not need to run through the function again it will simply use the cached value. If you used methods instead VueJS will run through all of this methods again to display the value.

View the demo to see this in action and remember to change the app.message value to see the reactiveness of the computed value.

Demo

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email