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

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
7 Hrs
25 Min
35 Seg

Componentes asíncronos

23/27

Reading

As our application grows, we are looking for ways to improve its performance. It makes a lot of sense to do Lazy Loading on routes, since you only open one route at a time. Therefore, you don't need to load all the contents of the routes at once.

...

Register or login to read the rest of the content.

Contributions 16

Questions 1

Sort by:

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

¿Qué te ha parecido? ¿Conocías keep-alive? ¿Lo has usado alguna vez? Para mí esta es de las mejores clases del curso.

Interesante lo del keep-alive, pero entonces me viene a la mente una duda:

Estamos encerrando TODO el componente en un keep alive, ¿Eso significa que no se volverá a cargar nunca más? (Hasta que recarguemos la página obviamente)

Si ese es el caso, entonces no podría refrescar los datos cada vez que cambie de componente ya que sus hooks no se ejecutarían porque ya estarían cargados, y algo que me gusta de Vue es que al volver a cargar el componente puedo refrescar sus datos

Justo cuando pensaba que este curso y Vue no me podrían sorprender más, aparece esta súper clase! Siento que el profe me ha transmitido mucho conocimiento y pasión por Vue. Si lees, gracias Jorge Baumann!

Con Vue3 tuve varios errores y no entendía el porque, luego revisé la documentación y para componentes asíncronos se cargan así:

import { defineAsyncComponent } from 'vue'
.
.
.
components: {
    ActiveSkills: defineAsyncComponent(() =>
      import(/* webpackChunkName: "ActiveSkills" */ './ActiveSkills'),
    ),
    PassiveSkills: defineAsyncComponent(() =>
      import(/* webpackChunkName: "PassiveSkills" */ './PassiveSkills'),
    ),
  },

Con eso ya funciona como el ejemplo de la clase.

Lo que más amo de Vue es su simpleza para lograr cosas complejas, aprendí muchas cosas super útiles en esta clase.

Que interesante va todo el curso🤩 estoy ansiosa por terminar

Excelente clase del curso, voy a investigar más sobre keep alive porque tengo varias dudas sobre si vuelve a hacer peticiones o no al server cuando necesite refrescar los datos.

Cuando realize el ejercicio note que no se piden de nuevo las imagenes por que quedan en cache, lo probe con Mozilla y Chrome aunque me parecio muy interesate keep alive.

Esta clase estuvo super emocionante !

No tenia idea del poder que Lazy Loading con un Keep-alive nos podría brindar en el rendimiento de nuestra aplicación con Vue, genial 🤯

Genial 🤯

Ya me habia tocado trabajar con Keep-Alive, tenia un componente con un render de un Mapbox que se podia ocultar, y recargaba todo el componente cuando lo mostraba de nuevo, muy pesado estar solicitando mapas cada momento!
Gran forma de produndizarlo…👍👍

Pregunta acerca del juego, Los Skills pasivos no tiene Runas? trato de a los Skills pasivos pintarles las rrunas con su nombre y me sale runas undefined

Siempre que me acerco a Vue.js no deja de sorprenderme con alguna novedad, definitivamente esta fue la gran sorpresa, no tenía ni idea de esta potente característica la cual asumo que con React por ejemplo es posible pero no de una manera tan sencilla.
Saludos compañeros y profesor.

Aunque no he probado React, creo que fue una buena elección elegir Vue, al usarlo con pug, todo queda sencillo, legible, y de rápido desarrollo. Se siente lo mismo que trabajar con Python en el Backend. Un problema? estas sencillas lineas de código y pum, todo listo…💪🏽

Sonará extraño, pero llevo haciendo este curso con React jajaja. En mi investigación para hacer todo lo de esta clase en React he aprendido muchísimo y al parecer no existe algo como keep-alive por lo que opte por simplemente hacer uso de css para ocultar los componentes y de esta manera no cargar las imágenes cada vez que las mostremos, lo malo de hacerlo de esta manera es que ambos componentes se cargan en simultaneo

So far all we've done is code splitting, that is, chopping up the code (actually Webpack did it for us: https://webpack.js.org/guides/code-splitting/). And this is so because we are showing the 2 components at the same time, therefore both are loaded at the same time and there is no lazy load.What can be more interesting is to have 2 buttons, each one associated to a component, and by default only load the active skills. When pressing the button of the passive skills, load the content of this other component, that is to say, to make lazy loading (now yes). Let's do it:Dynamic componentsBefore we can do this, we need to review the dynamic components: https://es.vuejs.org/v2/guide/components.html#Componentes-dinamicosEn summary, we have a new tag with the is property, which receives as value the name of the component we want to load.We can load several components, for example:import ComponentA from './ComponentA'import ComponentB from './ComponentB'And then use them like this:Or like this:computed: { selectedComponent () { return this.value === 'B' ? ComponentB : ComponentA }}}If value is equal to B, we load component B, otherwise, we load component A.This is what we are going to do with the skills components, use the tag and load the component we need with is. Let's go for it!Asynchronous dynamic components 🤯Let's start by changing the HTML of our component /Hero/HeroSkills/Index.vue:Let's create a new variable in the data to control which component is active and thus which one to display:data () { return { activeComponent: 'ActiveSkills' }}And some computed properties:computed: { /** * Dynamyc props for async dynamic components * @returns {String} */ // With this we are generating dynamic 'props' // If the component is ActiveSkills pass as props the active ones, if not, the passive ones componentProps () { return this.activeComponent === 'ActiveSkills' ? this.skills.active : this.skills.passive }, // Tells us if the component 'PassiveSkills' is active or not isPassiveSkillsActive () { return this.activeComponent === 'PassiveSkills' }}}In this part we make a brief emphasis.We close our eyes and think 'How wonderful computed properties are!' This is the power of computed properties.The rule I follow to know when to use them is: 'Always'. Abuse computed and everything will be fine.We have generated, through componentProps a dynamic prop (which we pass from comp. parent to child). This is necessary because we have dynamic components, therefore the props can not be static as we did before.Finally, we have the method that makes a component or another is loaded, when we click:methods: { changeComponent (component) { this.activeComponent = component }}The complete code would look like this:This is what our app looks like now:It looks in 2 columns because the app is responsive and this is how it looks on small screens. Now if we look at the network tab of the developer tools, we see that only the ActiveSkills component has loaded. This is great! Without closing the Network tab of the browser, we click on the Passive button, we will see how the other component is loaded.We have done lazy load of components by just refactoring a couple of lines. Now you can apply this method to all your projects 👏.Keep AliveHowever, I have a (not so good) news to give you. By doing this tab switch, i.e. switching from ActiveSkills component to PassiveSkills (or vice versa) multiple times, we are again making image load requests. Look what happened when doing the Active > Passive > Active flow:We loaded each image multiple times, in this case 3 times. Each time we change 'tabs', the component is destroyed, therefore the skill images have to be reloaded to be rendered.This is not a good practice, as we would be making unnecessary requests to load content that we had loaded before.This did not happen when we had synchronous components!To see how the component is created and destroyed with this lazy loading technique, we can put the code below in the /HeroSkills/PassiveSkills.vue:created () { console.log('CREATED!')},destroyed () { console.log('DESTROYED!')}Now, try again to switch between active and passive skill components. You can see how the logs come out in the browser's console. Vue has a solution for this and it's called Keep Alive. It's one of the features I like the most, for how complex it could get.> 📗 Keep Alive official documentation: https://es.vuejs.org/v2/guide/components-dynamic-async.html#keep-alive-con-Componentes-Dinamicos & https://es.vuejs.org/v2/api/#keep-aliveEsta definition, taken from the official documentation, I think it's perfect:> Keep Alive is mainly used to preserve the state of components or avoid re-rendering.Just what we want, that they are not loaded again, in this case, the images.Using it is as easy as wrapping the component we want to keep alive with the tag : So, we use keep-alive in our component and test. The HTML of the /Hero/HeroSkills/Index.vue should look like this:In this topic we have seen, Asynchronous Components, Dynamic Components, Dynamic Asynchronous Components with Dynamic Props and Keep Alive. 😍In the next one, we are going to finish with this view, where we will load the items (⚔️) of our character.", "url" : "https://platzi.com/clases/1856-avanzado-vue/27769-componentes-asincronos/", "wordCount" : "52", "publisher" : { "type" : "Organization", "name" : "Platzi INC" } }