[Nuxt3] Dynamic component

jellykelly·2025년 2월 10일
0

Nuxt

목록 보기
4/8
post-thumbnail

Nuxt3에서는 컴포넌트(화면에 렌더되는 태그)를 동적으로 설정할 수 있습니다. 이때, 직접 import하거나 resolveComponent 를 사용해야 합니다.

resolveComponent

resolveComponent를 사용하여 동적 요소를 처리할 경우, 컴포넌트의 이름 외에는 다른 값을 삽입하지 않아야 합니다. 이름은 반드시 문자열이어야 하며, 변수를 사용할 수 없습니다.

<script setup lang="ts">
import { SomeComponent } from '#components'

const MyButton = resolveComponent('MyButton')
</script>

<template>
  <component :is="clickable ? MyButton : 'div'" />
  <component :is="SomeComponent" />
</template>

적용 예시

공통된 디자인을 가진 버튼 컴포넌트가 있으며, 기능에 따라 <button> 태그 또는 <a> 태그로 적용해야 하는 경우가 있습니다. 이럴 때 동적 컴포넌트를 활용하면 유용합니다.

BaseButton.vue

<template>
  <component
    :is="componentType"
    :to="to"
    :type="to ? null : type"
    :id="id"
    :class="[
      'btn',
      {
        [`btn__${color}`]: color,
        [`btn__${size}`]: size,
      },
      customClass,
    ]"
    :disabled="to ? undefined : disabled"
  >
    <span class="btn__text">{{ label }}</span>
  </component>
</template>

<script lang="ts" setup>
import { resolveComponent, computed } from 'vue';

const props = defineProps({
  to: {
    type: String,
    default: undefined,
  },
  // 기타 props 정의
});

const componentType = computed(() => (props.to ? resolveComponent('NuxtLink') : 'button'));
</script>

componentTypeprops.to 값을 확인하여 to 속성이 존재하면 <NuxtLink>로, 존재하지 않으면 <button> 태그로 렌더링되도록 설정되었습니다.
<NuxtLink to="">는 브라우저에서 <a href="">로 렌더링 됩니다.

Parent.vue

<CommonButton id="btn" label="버튼으로 렌더링" />
<CommonButton to="/custom" class="new-btn" color="blue" label="a태그로 렌더링" />

실제 HTML 렌더링 결과

<button type="button" id="btn" class="btn btn__navy">버튼으로 렌더링</button>
<a href="/custom" class="btn btn__blue new-btn">a태그로 렌더링</a>

이와 같은 방식으로 Nuxt3의 동적 컴포넌트를 활용하면, 보다 유연하고 확장성 있는 컴포넌트 설계가 가능합니다. 🤗

profile
Hawaiian pizza with extra pineapples please! 🥤

0개의 댓글