Load components when needed with Vue async components

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In large applications, dividing the application into smaller chunks is often times necessary. In this lesson, we will look at how vue loads async components into your application.

[00:00] Let's create a Vue component. It will be the component that we will load asynchronously. The content is not important, since we only want to show it.

[00:10] Let's just write hello from Async. Now, let's register the component globally in the main JS file. This is a factory function that takes the resolve method as a first parameter.

[00:22] Here, we can use require in order to tell webpack to split this in a separate chunk, and it will call resolve when the component loads. This is known as call splitting and allows us to load a piece of code at runtime, just like Node.js does.

[00:38] Let's go back to the app component and use the Async component there. Now, if we run the project, we'll see that the Async component is loaded.

[00:51] We take a look at the network tab in the developer tools. We see that there are two files loaded, the app.js and [indecipherable] , which is the common chunk created for the Async component, but they both have loaded at boot time.

[01:04] That's a bit useless, because what we want is to load that component conditionally. For that, we can create a variable that will work as a flag. Then let's create a button, "Load Async Component." On the click event, we're going to change the variable to true.

[01:26] The idea is that we load asynchronously that component when that variable is true. For that, we need to use the Vue for directive, so that component will be created when it meets that condition. Let's run this again and see what happens.

[01:42] As you can see, only the app.js component is loaded, but when we click the button, the assign component chunk is now conditionally loaded from the server. Since the loading is asynchronous, you can defer it as much as you want, for example, if you make an HTTP call to the server.

[02:00] Let's go ahead and illustrate with a set timeout. We can write the console log just when we request the component and another when it's loaded. Then let's defer this by two seconds. If we click now, we see, "Loading," and after two seconds, it loads the Async component and it shows, "Loaded."

[02:27] Another way to write this asynchronous function is if you use webpack tool and [indecipherable] . You can use the import function. That returns a promise which is understood by Vue component factory function as well.

[02:42] If we try this again, we'll see it's working the same way it was before.