본문 바로가기
카테고리 없음

Vue3에서의 Dynamic Components: 더 깔끔하고 직관적으로!

by 유형제맘 2025. 7. 28.

동적 컴포넌트란?

동적 컴포넌트(Dynamic Component) 는 상황에 따라 렌더링할 컴포넌트를 바꿔야 할 때 사용하는 기능이에요. 예를 들어 탭 UI에서 클릭한 탭에 따라 다른 컴포넌트를 보여주고 싶을 때 사용하죠.

Vue2 방식 복습

Vue2에서는 <component> 태그와 :is 속성을 사용해 동적 컴포넌트를 이렇게 렌더링했어요.

<template>
  <component :is="currentComponent"></component>
</template>

<script>
export default {
  data() {
    return {
      currentComponent: 'UserProfile'
    }
  },
  components: {
    UserProfile,
    UserPosts
  }
}
</script>

Vue3에서의 주요 개선점

1. <script setup>과 함께 더 간결해짐
Vue3에서는 <script setup> 과 Composition API를 활용하면서 동적 컴포넌트 등록과 사용이 훨씬 직관적이 되었어요.

<template>
  <component :is="currentComponent" />
</template>

<script setup>
import UserProfile from './UserProfile.vue'
import UserPosts from './UserPosts.vue'

const currentComponent = ref('UserProfile')

const components = {
  UserProfile,
  UserPosts
}
</script>

Vue3에서는 컴포넌트 이름 문자열을 넘길 때 components 옵션에 등록되어 있어야 인식됩니다. 하지만 :is="components[current]" 처럼 객체 자체를 넘기는 방식도 가능해졌어요.

2. 컴포넌트 자체를 바인딩할 수 있음
Vue2에선 문자열만 바인딩하는 게 일반적이었지만, Vue3에선 컴포넌트 자체도 넘길 수 있어요.

<template>
  <component :is="currentComponent" />
</template>

<script setup>
import UserProfile from './UserProfile.vue'
import UserPosts from './UserPosts.vue'

const currentComponent = ref(UserProfile)
</script>

ref(UserProfile)처럼 아예 컴포넌트를 넘겨주면, 문자열 등록이나 components 옵션 없이도 렌더링 가능해요. 이게 Vue3의 큰 개선점 중 하나예요.

3. <KeepAlive>와 함께 사용 가능
Vue3에서도 <KeepAlive>는 여전히 유용하며, 동적 컴포넌트의 상태를 유지하고 싶을 때 함께 사용합니다.

<template>
  <keep-alive>
    <component :is="currentComponent" />
  </keep-alive>
</template>

동적 컴포넌트 UI 예시 (탭 메뉴)

<template>
  <div>
    <button @click="currentComponent = UserProfile">프로필</button>
    <button @click="currentComponent = UserPosts">게시글</button>

    <component :is="currentComponent" />
  </div>
</template>

<script setup>
import UserProfile from './UserProfile.vue'
import UserPosts from './UserPosts.vue'

const currentComponent = ref(UserProfile)
</script>

마무리 요약

항목 Vue2 Vue3 개선점
동적 컴포넌트 등록 문자열로만 (UserProfile) 컴포넌트 자체 전달 가능
컴포넌트 관리 components 옵션 필수 import로 바로 사용 가능
<script setup> 호환 불가능 완전 호환, 더 간결함

Vue3에서는 동적 컴포넌트를 더 직관적이고 유연하게 사용할 수 있습니다. 특히 <script setup>과 함께 쓰면 코드가 훨씬 짧아지고, 컴포넌트를 직접 넘기는 방식은 유지보수성과 타입 안정성까지 챙길 수 있어요. 탭, 폼 스텝, 조건부 페이지 등 다양한 UI에 활용해보세요!