The use of Vue3DefileAsyncComponentFunctionality allows us to lazily load components, which in other words, creates an asynchronous component that loads only when needed.

This is a good way to improve the initial page load because our application will load in smaller chunks rather than having to load every component at page load time.

In this article, we’ll learn all about defineAsyncComponent and an example of lazy loading pop-ups.

DefineAsyncComponent is what?

const AsyncComp = defineAsyncComponent( () => new Promise((resolve, reject) => { resolve({ template: '<div>I am async! </div>' }) }) )Copy the code

DefineAsyncComponent can accept a factory function that returns a Promise. The Promise’s resolve callback should be invoked after the server returns the component definition. You can also call reject(Reason) to indicate a load failure.

DefineAsyncComponent can be imported from vue using:

import { defineAsyncComponent } from "vue"
// simple usage
const LoginPopup = defineAsyncComponent(() => import("./components/LoginPopup.vue"))
Copy the code

This is the simplest method of defineAsyncComponent. For higher order usage, defineAsyncComponent can accept an object:

Const AsyncPopup = defineAsyncComponent({loader: () => import("./ loginpopup.vue "), // loadingComponent to use when loading asynchronous components: LoadingComponent, / / loading fail to use the component errorComponent: errorComponent, / / delay before displaying LoadingComponent | default value: 200 delay (ms) : 1000, // If timeout is provided and the loading time of the component exceeds the set value, the error component will be displayed // Default: Infinity (i.e., never timeout, in ms) timeout: 3000})Copy the code

The basics have been introduced, then, let’s do 🌰.

Load the Popup component asynchronously using defineAsyncComponent

In this example, we will use a login pop-up triggered by clicking a button. We do not need our application to load this component every time it is loaded, because it is only needed when the user performs a specific action. Here is the implementation of the LOGIN component:

// LoginPopup.vue <template> <div class="popup"> <div class="content"> <h4> Login to your account </h4> <input type="text" placeholder="Email" /> <input type="password" placeholder="Password" /> <button> Log in </button> </div> </div> </template> <script> </script> <style scoped> .popup { position: fixed; width: 100%; top: ; left: ; height: 100%; Background-color: rgba(,, 0.2); display: flex; justify-content: center; align-items: center; } .content { min-width: 200px; width: 30%; background: #fff; height: 200px; padding: 10px; border-radius: 5px; } input[type="text"], input[type="password"] { border: ; outline: ; border-bottom: 1px solid #eee; width: 80%; margin: auto; The font - size: 0.5 em. } button { border: ; margin-top: 50px; background-color:#8e44ad; color: #fff; padding: 5px 10px; The font - size: 0.5 em. } </style>Copy the code

Import it in other components:

<template>
  <button @click="show = true"> Login </button>
  <login-popup v-if="show" />
</template>

<script>
import LoginPopup from './components/LoginPopup.vue'
export default {
  components: { LoginPopup },
  data() {
    return {
      show: false
    }
  }
}
</script>
Copy the code

We can use defineAsyncComponent and only load it when we need it (use V-if to toggle when the button is clicked).

<! -- Use defineAsyncComponent --> <template> <button @click="show = true"> Login </button> <login-popup v-if="show" /> </template> <script> import { defineAsyncComponent } from 'vue' export default { components: { "LoginPopup" : defineAsyncComponent(() => import('./components/LoginPopup.vue')) }, data() { return { show: false } } } </script>Copy the code

This one looks pretty much the same as the one above. Don’t worry, let’sF12Open the console.

If we don’t usedefineAsyncComponentOnce our page loads, we’ll see our application get from the serverLoginPopup.vue. Although the performance problem is not as severe in this example, if we had dozens of components doing this, it would make a performance difference.However, if we usedefineAsyncComponentLooking at the same TAB, you’ll notice that when our page loads,LoginPopup.vueNo, because it hasn’t been loaded yet.However, if we toggle the button, we can see it:This helps us achieve optimal performance.

conclusion

DefineAsyncComponent is useful when building large projects that include many components. When we use lazy loading components, we load pages faster, improve the user experience, and ultimately improve app retention and conversion.

juejin.cn/post/698790…