To load components only when they’re needed, we can load components asynchronously.
We can also use the Suspense
component to render components with a fallback message that’s displayed when it’s loading.
In this article, we’ll look at how to create async components and use the Suspense
component to render them.
Vue 3 Suspense Component and Create Async Components
The Vue 3 Suspense
has the default
slot to render the dynamic components we want.
The fallback
slot lets us display a fallback message that’s rendered when the component is loading.
We can define async components with the defineAsyncComponent
function.
To use them together, we can write the following:
main.js
import { createApp, defineAsyncComponent } from "vue";
import App from "./App.vue";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const app = createApp(App);
const HelloWorldAsync = defineAsyncComponent(async () => {
await sleep(2000);
return import("./components/HelloWorld.vue");
});
app.component("hello-world", HelloWorldAsync);
app.mount("#app");
App.vue
<template>
<Suspense>
<template #default>
<hello-world />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</template>
<script>
export default {
name: "App",
};
</script>
components/HelloWorld.vue
<template>
<div class="hello">hello world</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
},
};
</script>
In the main.js
file, we have the sleep
function to simulate a delay in loading the component.
Then we create the Vue app with the createApp
function.
Next, we call defineAsyncComponenty
function that takes a function that returns a promise that resolves a component.
We call sleep
to add a 2000 ms delay.
Then we return the promise with the component, which we get with the import
function with the path to the component.
Then we register the component with the app.component
method.
Next, in App.vue
, we add the Suspense
component with the default
slot having the main content we want to display.
And the fallback
slot having the content that’s displayed when the component in the default
slot is loading.
HelloWorld.vue
has the content we want to display.
As a result, we should see the ‘Loading…’ message displayed for 2 seconds and then see ‘hello world’ displayed after that.
Conclusion
We can use the Vue 3 Suspense
component with async components to load components dynamically in an async manner.
The Suspense
component lets us display a loading message for the user when the async component is being loaded.