Propiedades computadas en objetos, con reactive():
const persona = reactive({
nombre: "Felipe",
apellido: "Perez",
edad: 20,
nombreCompleto: computed(() => {
return `${persona.nombre} ${persona.apellido}`;
}),
});
Introducción
¿Qué aprenderás en este curso?
Introducción a Vue CLI
Estructura del proyecto
Built-in Components
Componentes dinámicos
Componentes asíncronos
Transiciones
Teleports
Componentes personalizados
Virtual DOM
Entendiendo el ciclo de vida de los componentes
Explorando los primeros hooks del ciclo de vida de Vue
Mixins
Composition API
Introducción a Composition API
Ciclo de vida en Composition API
Variables reactivas con ref y reactive
Watch
Computed
Uso de props
Uso de context
Provide / Inject
Template refs
Composition vs. Options
Script setup
Cierre del curso
Hora de poner tu conocimiento en práctica
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
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:
ref
to create reactive properties firstName
and lastName
.computed
to declare fullName
, which will concatenate firstName
and lastName
.setup
return so that the template can find them.Although computed properties are powerful, it is crucial to know how to handle them properly to avoid problems:
this
inside setup
: With Composition API, the setup
function cannot access this
objects as in Options API. Be careful when migrating code.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
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
Want to see more contributions, questions and answers from the community?