Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically import Vue 3 component?

According this article I would like to import component to view dynamically to my Vue 3 app. The code of the view looks like:

<template>
  <div class="page">
      <latest-box v-if="showLatestBox" />
  </div>
</template>


<script>
// @ is an alias to /src
// This works well. 
//import LatestBox from '@/components/LatestBox.vue'


export default {
    name: 'Page 1',

    data() {
        return {
            showLatestBox: true,
        }
    },

    components: {
        LatestBox: () => import('@/components/LatestBox.vue')  // This does not work
    }
}
</script>

Code does not throw any errors but I dont see the component on the page. If I use first import style it works. Am I missing somethig?

like image 593
Čamo Avatar asked Jan 20 '26 11:01

Čamo


1 Answers

You need to use defineAsyncComponent in Vue 3 to lazy load components

import { defineAsyncComponent } from 'vue'
...
    components: {
        LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
    }

https://v3-migration.vuejs.org/breaking-changes/async-components.html#overview

like image 100
user16354282 Avatar answered Jan 23 '26 02:01

user16354282