You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
4 Hrs
40 Min
58 Seg

Computed

16/23
Resources

How to use computed properties in Vue JS with Composition API?

Vue JS has revolutionized the way we interact with data in web applications, and computed properties are a key part of making it even more efficient. With Vue's Composition API, we can handle these properties in a more flexible and modular way. Here's how to use them in this new syntax and their main benefits.

What are computed properties?

Computed properties are declarative functions that rely on reactive properties to return a result. Unlike simple functions, computed properties are efficiently cached until their dependencies change, avoiding unnecessary processing and optimizing performance.

Advantages of using computed properties:

  • Readability: code is cleaner and easier to understand.
  • Efficiency: Vue caches computed properties until one of their dependencies changes.
  • Reusability: They facilitate code reuse, reducing duplication.

How to implement computed properties with Composition API?

Implementing computed properties in Composition API follows a clear and simple logic. Let's analyze how we can apply it with a simple example: concatenate a first and last name into a complete string.

import { ref, computed } from 'vue';
export default { setup() { const firstName = ref('Diana'); const lastName = ref('Martinez');
 const fullName = computed(() => `${firstName.value}  ${lastName .value}`);
 return { firstName, lastName, fullName, fullName, }; }}} }

Key steps:

  1. Define reactive variables: we use ref to create reactive properties firstName and lastName.
  2. Create computed property: We use computed to declare fullName, which will concatenate firstName and lastName.
  3. Return properties: We return them in the setup return so that the template can find them.

What are the best practices when using computed functions?

Although computed properties are powerful, it is crucial to know how to handle them properly to avoid problems:

  • Caching: By having reactive dependencies, Vue only recomputes the computed property when a dependency changes.
  • Avoid infinite loops: When creating computed properties, make sure you don't have recursive dependencies that can cause an infinite loop.
  • Do not use this inside setup: With Composition API, the setup function cannot access this objects as in Options API. Be careful when migrating code.

How do Composition API and Options API compare when using computed properties?

In the Options API syntax, computed properties are defined using computed as a property inside a Vue object. Composition API follows a functional approach thanks to pure JavaScript functions, which makes the code more modular and easily maintainable. This transition not only improves code clarity, but also makes it easier to understand reactivity in Vue JS.

We recommend that you compare code from projects implemented with Options API and Composition API to observe the differences in readability and efficiency.

Explore how computed properties can increase the potential of your applications and act creatively to develop innovative solutions! And don't forget to share your experiences and challenges in the community - keep learning, and see you in the next class!

Contributions 5

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Propiedades computadas en objetos, con reactive():

const persona = reactive({
  nombre: "Felipe",
  apellido: "Perez",
  edad: 20,
  nombreCompleto: computed(() => {
    return `${persona.nombre} ${persona.apellido}`;
  }),
 });

Codigo de esta clase

<template>
  <div>{{ fullname }}</div>
</template>

<script>
import { ref, computed } from "vue";

export default {
  setup() {
    const firstName = ref("Dufainder");
    const lastName = ref("Bedoya");

    const fullName = computed(() => {
      return `${firstName.value} ${lastName.value}`;
    });

    return {
      fullName,
    };
  },
};
</script>

Otra forma de hacerlo, me parece que el código queda un poco más limpio, ¿qué opinan?

<template>
  <h2>{{ fullName }}</h2>
</template>

<script>
import { ref, computed } from "vue"

export default {
  setup() {
    const firstName = ref("John")
    const lastName = ref("Doe")

    return {
      fullName: computed(() => `${firstName.value} ${lastName.value}`)
    }
  }
}
</script>

Mi reto con computed haciendo que reciba un valor por parámetro:

<template>
  <div>
    <button @click="estado = !estado">Cambiar valor</button>
  </div>
  <div><button @click="miobj.count++">Aumentar valor</button></div>
  <div><button @click="proximo = 0">Resetear</button></div>
  <div v-show="estado">¡Apareci!</div>
  <div>{{ miobj.count }}</div>
  <div>Siguiente valor: {{ proximo }}</div>
</template>

<script setup>
import { ref, reactive, watch, computed } from "vue";

const estado = ref(true);
const miobj = reactive({ count: 0 });

// const proximo = computed(() => miobj.count + 1);

const proximo = computed({
  get: () => miobj.count + 1,
  set: (valor) => {
    miobj.count = valor;
  },
});

watch(proximo, (newValue, oldValue) => {
  console.log("Anterior", oldValue);
  console.log("Nuevo", newValue);
  if (miobj.count > 10) {
    proximo.value = 0;
  }
});
</script>

Entonces con la funcion setup(){} hacemos todo lo que haciamos con options API pero de una forma digamos “manual” pero más sencillo. Solo es acostumbrarse a ya no declarar las variables en data sino usar ref o reactive