Computed properties are a powerful feature in Vue that allow you to derive and transform data dynamically based on reactive state. When used correctly, they make your code cleaner, more efficient, and easier to maintain. However, improper usage can lead to unexpected bugs and performance issues.
In this article, we’ll cover good practices for working with computed properties in Vue, ensuring you get the most out of them:)
Enjoy!
🤔 What Are Computed Properties?
Computed properties are special properties in Vue that automatically update when their dependencies change. Unlike methods, they are cached until their dependencies change, making them an efficient choice for derived state.
Let's take a look at following basic example:
<script setup>
import { ref, computed } from 'vue';
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
</script>
<template>
<div>
<p>Full Name: {{ fullName }}</p>
</div>
</template>
Here, fullName
automatically updates whenever firstName
or lastName
changes, without requiring manual re-calculation.
🟢 Good Practices for Computed Properties
As we already know what Vue Computed Properties are, let's now dive into the good practices.
1. Use Computed Properties for Derived State
Avoid using computed properties for directly manipulating or setting state. Instead, reserve them for calculations or transformations based on existing state.
Use:
const cartItems = ref([{ price: 10 }, { price: 15 }]);
const totalPrice = computed(() => cartItems.value.reduce((sum, item) => sum + item.price, 0));
Instead of:
const cartItems = ref([]);
const addItem = computed(() => (item) => cartItems.value.push(item));
// Use a method for state modification instead
2. Avoid Side Effects in Computed Properties
Computed properties should remain pure and free of side effects. This ensures they are predictable and only serve to compute values.
Use:
const items = ref([1, 2, 3]);
const doubledItems = computed(() => items.value.map(item => item * 2));
Instead of:
const items = ref([1, 2, 3]);
const doubledItems = computed(() => {
console.log('Doubled items calculated'); // Side effect
return items.value.map(item => item * 2);
});
3. Cache Expensive Computations
One of the primary benefits of computed properties is their caching mechanism. Leverage this for expensive calculations to avoid unnecessary re-computations.
const largeData = ref([...Array(1000000).keys()]);
const sum = computed(() => largeData.value.reduce((a, b) => a + b, 0));
4. Use Getters and Setters for Bidirectional Computed Properties
When you need a computed property that can also set values, use getters and setters. This is useful for derived state that affects other reactive data.
<script setup>
import { ref, computed } from 'vue';
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed({
get: () => `${firstName.value} ${lastName.value}`,
set: (newValue) => {
const [first, last] = newValue.split(' ');
firstName.value = first;
lastName.value = last;
}
});
</script>
<template>
<input v-model="fullName" />
<p>Full Name: {{ fullName }}</p>
</template>
5. Break Down Complex Computed Properties
For readability and maintainability, avoid overly complex computed properties. Break them into smaller, reusable pieces if necessary.
const basePrice = ref(100);
const tax = ref(0.1);
const priceWithTax = computed(() => basePrice.value * (1 + tax.value));
const formattedPrice = computed(() => `$${priceWithTax.value.toFixed(2)}`);
📖 Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉
✅ Summary
Computed properties are an essential tool in Vue for managing derived state efficiently. By following best practices, such as avoiding side effects, leveraging caching, and breaking down complex logic, you can ensure your applications remain performant and maintainable. Start applying these tips today to write cleaner and more robust Vue components!
Take care and see you next time!
And happy coding as always 🖥️
Top comments (1)
Maybe I don't know what is best practice but part of advices can get from read vuejs.org and other part its could be fixed by installed eslint with some plugins for vue