Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make vue3 import async dynamic component work?

Tags:

vue.js

vuejs3

I am a beginner using vue3. We can use dynamic component like this:

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

   </component >
</template>

and I try to use dynamic component like this,but it is wrong:

export default {
  CommonLayout: () => import("./CommonLayout.vue"),
  EmptyLayout: () => import("./EmptyLayout.vue"),
  HeaderLayout: () => import("./HeaderLayout.vue"),
};
<script setup>
   import layouts from "@/components/Layout/index.js";
   const { default: Layout } = await layouts["CommonLayout"]();
</script>
<template>
  <Layout>
    something
  </Layout>
</template>

not error catch but the page show nothing. and the Layout is the same with CommonLayout:

enter image description here

like image 324
radiorz Avatar asked Oct 17 '25 00:10

radiorz


1 Answers

You need to use 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>
like image 140
Josh Avatar answered Oct 18 '25 17:10

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!