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

Time:05-13

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>

CodePudding user response:

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>
  • Related