Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Async Components Suspense Lazy Loading: Tutorial, Examples, FAQs & Interview Tips

Async Components

Async components let you load components lazily - only when they're needed. This reduces the initial bundle size and improves page load performance. Vue's defineAsyncComponent() wraps a dynamic import and handles loading/error states.

defineAsyncComponent and Suspense
<template>
  <div>
    <!-- Async component - loaded only when rendered -->
    <HeavyChart v-if="showChart" />
    <button @click="showChart = !showChart">Toggle Chart</button>

    <!-- With loading and error states -->
    <AdminPanel v-if="isAdmin" />
  </div>
</template>

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

// Simple async component - just a dynamic import
const HeavyChart = defineAsyncComponent(() =>
  import('./HeavyChart.vue')
)

// With options - loading state, error state, timeout
const AdminPanel = defineAsyncComponent({
  // The loader function
  loader: () => import('./AdminPanel.vue'),

  // Component to show while loading
  loadingComponent: {
    template: '<div class="loading-spinner">Loading...</div>'
  },

  // Delay before showing loading component (ms)
  delay: 200,

  // Component to show if loading fails
  errorComponent: {
    template: '<div class="error">Failed to load component</div>'
  },

  // Timeout - show error if loading takes too long
  timeout: 5000,

  // Called when loading fails
  onError(error, retry, fail, attempts) {
    if (attempts <= 3) {
      retry()  // retry up to 3 times
    } else {
      fail()
    }
  }
})

const showChart = ref(false)
const isAdmin = ref(true)
</script>
<!-- Suspense - handle async setup() in child components -->
<template>
  <div>
    <!-- Suspense wraps async components -->
    <Suspense>
      <!-- Default slot: shown when ready -->
      <template #default>
        <AsyncUserProfile :userId="userId" />
      </template>

      <!-- Fallback slot: shown while loading -->
      <template #fallback>
        <div class="skeleton">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-text"></div>
          <div class="skeleton-text short"></div>
        </div>
      </template>
    </Suspense>

    <!-- Combine with Transition for smooth loading -->
    <Suspense @pending="onPending" @resolve="onResolve" @fallback="onFallback">
      <template #default>
        <Transition name="fade" mode="out-in">
          <AsyncDashboard :key="currentPage" />
        </Transition>
      </template>
      <template #fallback>
        <LoadingSpinner />
      </template>
    </Suspense>
  </div>
</template>

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

const AsyncUserProfile = defineAsyncComponent(() => import('./UserProfile.vue'))
const AsyncDashboard   = defineAsyncComponent(() => import('./Dashboard.vue'))

const userId = ref(1)
const currentPage = ref('home')

function onPending()  { console.log('Loading started') }
function onResolve()  { console.log('Loading complete') }
function onFallback() { console.log('Showing fallback') }
</script>

<!-- AsyncUserProfile.vue - uses async setup() -->
<!-- <script setup> -->
<!-- const props = defineProps({ userId: Number }) -->
<!-- // await in setup() - Suspense waits for this -->
<!-- const user = await fetch(`/api/users/${props.userId}`).then(r => r.json()) -->
<!-- </script> -->

Deep Dive: Async Components in Real Projects

Understanding Async Components is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Async Components.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Async Components.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Async Components focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.