radiorz
radiorz

Reputation: 1879

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:

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>

Upvotes: 0

Views: 671

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

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>

Upvotes: 1

Related Questions