Computed Properties
Computed properties are one of the most powerful features of Vue.js for deriving values based on existing reactive data. They are essentially functions that are cached based on their reactive dependencies. This means they only re-evaluate when one of their dependencies changes, leading to performance optimizations.
What are they?
- Derived Data: Computed properties are used to calculate values that are derived from your component's data. Instead of performing complex calculations directly in your template, you define them as computed properties.
- Caching: Vue caches the result of a computed property. If the reactive dependencies haven't changed, Vue returns the cached result instead of re-running the function.
- Reactive: Computed properties are automatically updated whenever their dependencies change. This ensures your derived data is always in sync with your component's state.
- Read-Only by Default: Computed properties are read-only by default. You can't directly assign a new value to a computed property. If you need a writable property, use a method instead.
Defining Computed Properties
Computed properties are defined within the computed option of a Vue component.
<template>
<p>Full Name: {{ fullName }}</p>
<p>Is Active: {{ isActive }}</p>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe',
isActive: true
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
},
isActiveText() {
return this.isActive ? 'Active' : 'Inactive'
}
}
}
</script>
In this example:
fullNameis a computed property that concatenatesfirstNameandlastName.isActiveTextis a computed property that returns "Active" or "Inactive" based on theisActivedata property.
Accessing Computed Properties
You access computed properties just like regular data properties in your template. They are accessed using the property name (e.g., fullName, isActiveText).
Getters and Setters (Writable Computed Properties)
While computed properties are read-only by default, you can define both a get and a set function to make them writable.
<template>
<input type="text" v-model="fullName">
</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];
}
}
}
}
</script>
In this example:
- The
fullNamecomputed property now has asetfunction. - When the
fullNameproperty is modified (e.g., throughv-model), thesetfunction is called. - The
setfunction splits the new value into first and last names and updates the corresponding data properties.
When to Use Computed Properties
- Complex Calculations: When you need to perform calculations based on multiple data properties.
- Formatting Data: When you need to format data for display (e.g., dates, currencies).
- Derived State: When you need to derive a new state from existing data.
- Performance Optimization: When you want to avoid unnecessary re-calculations.
Computed Properties vs. Methods
| Feature | Computed Properties | Methods |
|---|---|---|
| Caching | Yes | No |
| Reactive | Yes | Yes (when called) |
| Read-Only | By default | Writable |
| Use Case | Derived data | Event handling, tasks |
| Template Usage | {{ propertyName }} |
{{ methodName() }} |
Key Differences:
- Caching: Computed properties are cached, while methods are not. This means computed properties are more efficient when the same calculation is needed multiple times.
- Execution: Computed properties are only executed when their dependencies change. Methods are executed every time they are called.
- Syntax: Computed properties are accessed like data properties, while methods are called like functions.
In general, use computed properties for derived data that needs to be reactive and cached. Use methods for tasks or event handling that don't necessarily need to be cached.