Vue.js async components

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

Victor
Open Source Engineer
Vue js
Published
April 26, 2021

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:

Hackages is an educational platform with the mission of improving developers and businesses' skills and helping them acquire new ones.
Home
Tutorials
Blog
Webinars