VUE

Vue 3 Asynchronous Components for Code Splitting

Boost your Vue 3 application's performance by implementing asynchronous components using `defineAsyncComponent`, enabling lazy loading and code splitting for faster initial page loads.

// main.js or router/index.js (example of using async components in routing)
import { createApp, defineAsyncComponent } from 'vue';
import App from './App.vue';

// Define an async component
const AsyncComponent = defineAsyncComponent(() =>
  import('./components/HeavyComponent.vue') // Path to your component
);

// If using Vue Router, you'd define it like this for routes:
/*
const routes = [
  {
    path: '/about',
    component: () => import('./views/AboutView.vue')
  }
];
*/

// App.vue (example usage within a template)
<template>
  <div>
    <h1>Main Application</h1>
    <button @click="showAsync = !showAsync">Toggle Heavy Component</button>
    <Suspense>
      <template #default>
        <AsyncComponent v-if="showAsync" />
      </template>
      <template #fallback>
        <div>Loading Heavy Component...</div>
      </template>
    </Suspense>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';

// Define the async component directly in setup for template usage
const AsyncComponent = defineAsyncComponent(() =>
  import('./components/HeavyComponent.vue')
);

const showAsync = ref(false);
</script>

<!-- components/HeavyComponent.vue -->
<template>
  <div class="heavy-component">
    <h3>This is a Heavy Component</h3>
    <p>Imagine this component has a lot of complex logic or renders a large amount of content.</p>
    <p>It's loaded only when needed!</p>
  </div>
</template>

<style scoped>
.heavy-component {
  border: 2px solid #42b983;
  padding: 20px;
  margin-top: 20px;
  background-color: #e6ffed;
}
</style>
How it works: `defineAsyncComponent` in Vue 3 allows you to define components that are loaded asynchronously, typically via webpack's code-splitting feature. This means the component's JavaScript bundle is only fetched and parsed when it's actually needed, significantly reducing the initial bundle size and improving application load times. It's often used with `<Suspense>` to show a loading fallback while the component is being fetched, providing a smoother user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs