DEV Community

Cover image for Good practices for Vue Computed Properties
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

9

Good practices for Vue Computed Properties

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>
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Instead of:

const cartItems = ref([]);
const addItem = computed(() => (item) => cartItems.value.push(item));
// Use a method for state modification instead
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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)}`);
Enter fullscreen mode Exit fullscreen mode

📖 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:

Vue School Link

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 🖥️

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (1)

Collapse
 
thefinn15 profile image
Timur

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay