How to use computed properties in Vue, with examples.

How to use Computed props in Vue.js
How to use Computed props in Vue.js
Vue computed props

If you’re new to Vue.js then you might not know how awesome computed properties are. There are so many cool things you can use them for, which really can help your components with readability and code reuse.

Here are some cool examples, of how you can use computed properties, hope they help:

1. Adding data properties together

Computed properties can be really handy when you want to use one or more data properties together.

Let’s create a component with two text boxes, one for a user’s first name and the other surname. Then display the full name underneath :

<template>
<div>
<div>
<input type="text" v-model="firstName" placeholder="First Name" />
</div>
<div>
<input type="text" v-model="surname" placeholder="Surname" />
</div>
Full Name: {{ fullName }}
</div>
</template>
<script>
export default {
name: 'user-name',
data: function () {
return {
firstName: "",
surname: ""
};
},
computed: {
fullName: function() {
return `${this.firstName} ${this.surname}`;
}
}
}

What’s happening?

All we’re doing in the computed prop is adding the first name to the surname. The computed property will then react to either the first name or surname changing and will then update fullName automatically, easy right!!

2. Conditional hiding elements

I find using computed props when hiding and showing elements makes it easier to read for other developers, as it doesn’t clutter up the HTML with business logic and makes it more maintainable if you want to add extra rules.

Let’s create a table which will show a list of users and if no users are assigned to the user's array then the table will not be displayed.

<template>
<div>
<h1>Users</h1>
<table v-if="hasUsers">
<tr>
<td v-for="user in users" :key="user.id">
{{ user.name }}
</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: 'users',
data: function () {
return {
users: []
};
},
computed: {
hasUsers: function() {
return this.users.length > 0;
}
}
}
</script>

What’s happening?

If you look at the table element it has v-if which is using the hasUser computed property. If true it will show the table, if false it will hide the table.

All the computed property is doing is checking that there is at least 1 in the user’s array, the computed prop will update any time the user’s array does. That’s it!

You could of course use v-if="users.length > 0" inside the template but who wants to go searching for that sort of logic in the template. This also makes it harder to make unit tests!

3. Disabling elements

This is similar to point 2 in terms of why you would use a computed property but used in the context of disabling elements.

Let’s create a textbox and button. The textbox is asking for the user’s age, if they’re under 18 the button will be disabled.

<template>
<div>
<input v-model.number="age" type="number" placeholder="Age" />
<button :disabled="underAge" id="btn" onclick="alert('Buy stuff')">Buy stuff</button>
</div>
</template>
<script>
export default {
name: 'conditional-disabling',
data: function () {
return {
age: null
};
},
computed: {
underAge: function () {
return this.age < 18;
}
}
}
</script>

What’s happening?

The underAge computed property is bound to the button using :disabled , the computed property will return true if the user’s age is under 18.

4. Filtering arrays

Really helpful when filtering lists with conditions and reduces the codebase. I’ve noticed when reviewing other developers code, they will use an event (e.g click or input) then set the data themselves. Which can get messy very quickly, the below should help with that.

Let’s build on the table of users we used for point 2. We will add a checkbox to filter active users. When checked it will show only active users, if not checked it will show only non-active users. We will also hard code some users in the data so we can see this baby working!

<template>
<div>
<h1>Users</h1>
Active: <input type="checkbox" v-model="active" />
<table v-if="hasUsers">
<tr v-for="user in filteredUsers" :key="user.id">
<td>
{{ user.name }}
</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: 'filter-users',
data: function () {
return {
active: true,
users: [
{ name: "Dave", active: true, id: 1 },
{ name: "Ste", active: false, id: 2 },
{ name: "James", active: true, id: 3 },
{ name: "Lee", active: true, id: 4 }
]
};
},
computed: {
filteredUsers: function() {
return this.users.filter(user => user.active == this.active);
},
hasUsers: function() {
return this.filteredUsers.length > 0;
}
}
}
</script>

What’s happening?

If you look in the v-for for the <tr> elements it’s now using the filterUsersprops instead of theusers.The filteredUsers prop will listen to any changes to the activedata or users data as they’re being used in the computed prop. This will then filter our list of users for us and the DOM will react. Wouldn't be that easy in jQuery!

If you have state management (Vuex), this would usually be a getter, if the user's array was stored in state.

5. Formating data

Let’s create a component which has a textbox and underneath it displays the value in caps.

<template>
<div>
<div>
<input v-model="name" type="text" placeholder="Name" />
</div>
Name in caps: {{ nameInCaps }}
</div>
</template>
<script>
export default {
name: 'Hello-World',
data: function () {
return {
name: ""
};
},
computed: {
nameInCaps: function() {
return this.name.toUpperCase();
}
}
}
</script>

What’s happening?

The computed prop is using the name data and changing it to upper case for us, how nice! You also use a concept of filters for this, which can be handy if you want to use them globally.

Conclusion

If haven't noticed by now, I love computed properties in Vue.Js. They just make working with Vue data so much easier and help to keep business logic out of your template, which is always helpful! I think it’s a good idea to get developers using computed props as much as possible.

The main issue I’ve noticed with other developers code is when to use watches over computed properties. If you look at the Vue documentation, it says you should try and use computed properties instead of watches when you can. I think this is because people don't know how powerful computed properties can be. It’s similar to when you should use CSS over javascript!

Written by

Full stack lead developer, from Manchester(UK)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store