Vue Async Components Vue 2

In Vue 2, async components were created by simply defining a component as a function that returned a promise, such as:

const asyncModal = () => import('./Modal.vue')

Or, for the more advanced component syntax with options:

const asyncModal = {
  component: () => import('./Modal.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
}

Example

Creating Async Components

To create an async component, you need to define a function that returns a Promise that resolves to the component definition. This function can be used as a factory function for the component, and Vue.js will take care of loading and rendering the component when required.

To demonstrate, let’s create a simple async component called ‘AsyncComponent’.

const AsyncComponent = () => ({
  component: import('./AsyncComponent.vue'),
  loading: LoadingComponent,
  error: ErrorComponent,
  delay: 200,
  timeout: 3000
});

In this example, we are using the import() function to load the component asynchronously. The loading and error properties define the components to be displayed while the component is being loaded and in case of an error, respectively. The delay property specifies the time (in milliseconds) to wait before displaying the loading component, and the timeout property sets a timeout for the loading process.

Using Async Components

To use the async component, register it in your Vue.js application. You can either register it globally or locally, depending on what you need.

To register the component globally, add the following code to your main.js file:

import Vue from 'vue';
import AsyncComponent from './AsyncComponent';
 
Vue.component('async-component', AsyncComponent);

To register the component locally, add it to the components property of your Vue instance:

import AsyncComponent from './AsyncComponent';
 
export default {
  components: {
    'async-component': AsyncComponent
  }
}

After registering the component, you can use it in your application just like any other Vue component:

<template>
  <div>
    <async-component></async-component>
  </div>
</template>

Reference

Working with Async Components in Vue.js | Reintech media