Vue — computed()
Basic computed
<template>
<div>
<p>First name: {{ firstName }}</p>
<p>Last name: {{ lastName }}</p>
<p>Full name: {{ fullName }}</p>
<button @click="changeName">Change</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
},
methods: {
changeName() {
this.firstName = 'Jane'
}
}
}
</script>
Getter and setter
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName: {
get() {
return `${this.firstName} ${this.lastName}`
},
set(newValue) {
const [first, last] = newValue.split(' ')
this.firstName = first
this.lastName = last
}
}
}
}
</script>
Computed vs methods
<!-- Computed: cached, only recalculates when deps change -->
<p>{{ fullName }}</p>
<!-- Methods: recalculates on every render -->
<p>{{ getFullName() }}</p>
Computed for filtering
<template>
<div>
<input v-model="search" placeholder="Search">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
search: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.search.toLowerCase())
)
}
}
}
</script>
Computed for sorting
<script>
computed: {
sortedItems() {
return [...this.items].sort((a, b) =>
a.name.localeCompare(b.name)
)
}
}
</script>
Mini Practice
- Create a computed property
- Use getter and setter
- Filter a list with computed
- Sort items with computed
Up Next
Continue with Watchers - Side effects.
Related Topics
Frequently Asked Questions about computed()
What is computed() in Vue?
computed() is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn computed()?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn computed().
Why is computed() important in Vue?
computed() is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.