简体   繁体   中英

Could vue3 <script setup> use component is, how to make it work?

I am new beginner of vue3 and found that vue have three way to write component:

  • <script setup>
  • normal-setup/composition api
  • options api.

I know how to use in normal composition api like this:

<script>
import CommonLayout from "@/components/Layout/CommonLayout.vue";
export default {
  components: {
    CommonLayout,
  },
  setup() {
    const layout = "CommonLayout";
    return { layout };
  },
};
</script>
<template>
  <div>
    {{ layout }}
    <component :is="layout">123</component>
  </div>
</template>

it really works.

but I try to use setup script, it failed:


<script setup>
import CommonLayout from "@/components/Layout/CommonLayout.vue";
const layout = "CommonLayout";
</script>
<template>
  <div>
    {{ layout }}
    <component :is="layout">123</component>
  </div>
</template>

<style></style>

You need to use imported name:

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

or dynamically:

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

or you can use alias

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM