如何动态导入Vue 3组件?

Čam*_*amo 11 javascript import components vue.js vuejs3

根据这篇文章,我想导入组件以动态查看我的 Vue 3 应用程序。视图的代码如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

代码不会引发任何错误,但我在页面上看不到该组件。如果我使用第一个导入样式,它就可以工作。我错过了什么吗?

小智 32

你需要defineAsyncComponent在Vue 3中使用来延迟加载组件

import { defineAsyncComponent } from 'vue'
...
    components: {
        LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
    }
Run Code Online (Sandbox Code Playgroud)

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

  • 由于链接现在重定向到 vuejs 首页,因此以下是相关指南的链接:https://vuejs.org/guide/components/async.html (3认同)