How to dynamically import Vue 3 component?
Asked Answered
B

1

13

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?

Breeze answered 28/7, 2021 at 11:10 Comment(0)
P
36

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

Potpourri answered 29/7, 2021 at 0:32 Comment(3)
As the link now redirects to the vuejs front page, here is the link to the related guide: vuejs.org/guide/components/async.htmlJehu
I love you - I needed this for a project I'm working on that supports many different types of complex editors, so only ever wanted to load the one that was actually needed.Occidentalize
This is great! Thank you. Works as a charm.Risteau

© 2022 - 2024 — McMap. All rights reserved.