VueJS - Computed Properties: A Beginner's Guide
Hello there, future Vue.js superstar! Today, we're going to embark on an exciting journey into the world of Computed Properties in Vue.js. Don't worry if you're new to programming – I'll be your friendly guide, and we'll take this step by step. By the end of this tutorial, you'll be amazed at how much you've learned!
What are Computed Properties?
Imagine you're baking a cake. You have ingredients (data), and you follow a recipe (logic) to create something delicious (computed property). In Vue.js, computed properties are like magical cake recipes that automatically update whenever their ingredients change!
Let's start with a simple example:
<template>
<div>
<p>First Name: {{ firstName }}</p>
<p>Last Name: {{ lastName }}</p>
<p>Full Name: {{ fullName }}</p>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
</script>
In this example, fullName
is our computed property. It's like a smart recipe that combines firstName
and lastName
to give us a complete name. The best part? Whenever firstName
or lastName
changes, fullName
updates automatically!
Why Use Computed Properties?
- Simplicity: They keep your template clean and easy to read.
- Performance: Vue caches the result and only re-computes when dependencies change.
- Dependability: They update automatically when their dependencies change.
Computed Properties vs Methods
"But wait," you might say, "couldn't we just use a method instead?" Great question! Let's compare:
<template>
<div>
<p>Computed: {{ reversedMessage }}</p>
<p>Method: {{ reverseMessage() }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue!'
}
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
},
methods: {
reverseMessage() {
return this.message.split('').reverse().join('')
}
}
}
</script>
Both reversedMessage
and reverseMessage()
do the same thing. But here's the secret sauce: computed properties are cached. If message
doesn't change, reversedMessage
won't recalculate. It's like having a super-efficient assistant who remembers previous results!
Computed Properties with Dependencies
Computed properties shine when they depend on multiple pieces of data. Let's look at a more complex example:
<template>
<div>
<input v-model="searchQuery" placeholder="Search todos">
<ul>
<li v-for="todo in filteredTodos" :key="todo.id">{{ todo.text }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
todos: [
{ id: 1, text: 'Learn Vue', completed: false },
{ id: 2, text: 'Build an app', completed: true },
{ id: 3, text: 'Master computed properties', completed: false }
]
}
},
computed: {
filteredTodos() {
return this.todos.filter(todo =>
todo.text.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
Here, filteredTodos
is like a smart filter. It watches both todos
and searchQuery
. When either changes, it updates the list automatically. Magic, right?
Get/Set in Computed Properties
Now, let's level up! Computed properties can have both a getter and a setter. It's like having a two-way recipe – you can read the result and modify the ingredients!
<template>
<div>
<p>Full Name: {{ fullName }}</p>
<button @click="changeFullName">Change Name</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
},
methods: {
changeFullName() {
this.fullName = 'Jane Smith'
}
}
}
</script>
In this example, fullName
is not just a recipe (getter) but also a reverse recipe (setter). When we change fullName
, it automatically updates firstName
and lastName
. It's like having a magical name-changing potion!
Computed Property Methods
Let's wrap up with a table of common methods you can use within computed properties:
Method | Description | Example |
---|---|---|
filter() |
Creates a new array with elements that pass a test | this.items.filter(item => item.price > 100) |
map() |
Creates a new array by transforming every element | this.items.map(item => item.name.toUpperCase()) |
reduce() |
Reduces an array to a single value | this.items.reduce((total, item) => total + item.price, 0) |
sort() |
Sorts the elements of an array | this.items.sort((a, b) => a.price - b.price) |
includes() |
Checks if an array contains a certain element | this.items.includes('apple') |
find() |
Returns the first element that passes a test | this.items.find(item => item.id === 3) |
Remember, these methods don't modify the original array, which is perfect for computed properties!
And there you have it, my eager learners! You've just mastered the art of computed properties in Vue.js. From simple calculations to complex filtering, you now have the power to make your Vue applications smarter and more efficient. Keep practicing, keep coding, and most importantly, keep having fun with Vue!
Credits: Image by storyset