A short introduction to Vue.js computed properties

A short introduction to Vue.js computed properties

Published 20. jul 2018 08:48 by Stein Ove Helset

Vue.js computed properties helps you to make computations and changes to your data variables.

Can't I just use expressions in the templates?

Well, you can. But you shouldn't (most of the times). Inside the templated you're limited to just one expression and in addition to that the template is made for showing the data, not working with it. That is what the computed properties are for. Here is a short example.


<template>
    <div>
        <b>First name: </b>{{ first_name }}<br>
        <b>Last name: </b>{{ first_name }}<br><br>
        
        {{ full_name_message }}
    </div>
</template>

<script>
export default {
    data() {
        return {
            first_name: 'John',
            last_name: 'Doe'
        }
    },
    computed: {
        full_name_message: function() { // Function for generating/computing the message
            const full_name = this.first_name + ' ' + this.last_name // Combine the first_name and the last name
            
            return 'Your full name is ' + full_name + '. It is ' + full_name.length + ' characters long!' // Return the message with full name and the number of characters
        }
    }
}
</script>

Isn't it just the same as a method?

A computed property might look like a method and indeed they are quite similar. The only difference is that a method must be called and not just referenced. A computed property is also cached, meaning that they will update when a reactive source has been updated. So if you reference the computed property multiple times it will re use the cached value, but if you do the same with a method it will do the calculation over and over again.

Share this post

Comments

No comments yet

Add comment