How to use computed properties in Vue, with examples.
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…