Vue.js async components

Victor
Hackages Blog
Published in
3 min readApr 17, 2019

--

Just like React and Angular, Vue.js gives you the possibility to lazy load some parts of your application.

But to start: what is lazy loading? When you have a large application, you do not want to load everything at the same time. Doing that will make your application slower and load data that the user might not even need. To solve that problem, you will split your application in smaller chunks and only load them when needed.

And, how can you do that? Easy peasy! In the code where you want to define your component, you just need to provide a function that returns a dynamic import of your component.

Now I will show you two ways to use it in your application:

  1. Route based

If you use the package vue-router, when defining the different routes you can just easily pass a dynamic import:

2. Local Registration

Here you can directly see that I use dynamic import to register my component:

Now, let’s take a look at a more advanced way to handle async components. Instead of returning directly the dynamic import, you can also use an object that has multiple keys.

https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components

In the example below, I have defined the component with a promise and a setTimout to show the utility of this format. Normally you use a dynamic import:

> If you liked what you just read: clap it away, share this post & feel free to leave me your comments or contact me at victor@hackages.io if you have any questions.

You can find more information about Hackages on our website. We’re a community driven company that offers high level training on the latests frameworks and technologies around JavaScript. We also love to contribute to open source and to organise free community events all around Europe! Check our upcoming training and events near you at https://hackages.io.

--

--