如何让vue3导入异步动态组件工作?

rad*_*orz 3 vue.js vuejs3

我是vue3的初学者。我们可以像这样使用动态组件:

<script setup>
import CommonLayout from "@/components/Layout/CommonLayout.vue";
</script>
<template>
  <component :is="CommonLayout>

   </component >
</template>
Run Code Online (Sandbox Code Playgroud)

我尝试使用这样的动态组件,但这是错误的:

<script setup>
import CommonLayout from "@/components/Layout/CommonLayout.vue";
</script>
<template>
  <component :is="CommonLayout>

   </component >
</template>
Run Code Online (Sandbox Code Playgroud)
<script setup>
   import layouts from "@/components/Layout/index.js";
   const { default: Layout } = await layouts["CommonLayout"]();
</script>
<template>
  <Layout>
    something
  </Layout>
</template>
Run Code Online (Sandbox Code Playgroud)

没有错误捕获,但页面没有显示任何内容。布局与 CommonLayout 相同:

在此输入图像描述

Jos*_*osh 6

您需要使用defineAsyncComponent

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

const CommonLayout = defineAsyncComponent(() => import("./CommonLayout.vue"))
const EmptyLayout = defineAsyncComponent(() => import("./EmptyLayout.vue"))
const HeaderLayout = defineAsyncComponent(() => import("./HeaderLayout.vue"))
</script>

<template>
  <component :is="CommonLayout></component>
  <component :is="EmptyLayout></component>
  <component :is="HeaderLayout></component>
</template>
Run Code Online (Sandbox Code Playgroud)