DEV Community

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

Posted on

12

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 πŸ–₯️

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (2)

Collapse
 
jhon_blair profile image
Jhon Blair β€’

This is such a great guide on Vue computed properties! I love how you explained everything in a clear and practical way. The tips on avoiding side effects and caching expensive computations are super helpful. Definitely going to use these best practices in my projects. Thanks for sharing really appreciate the effort you put into this!

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

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay