Vue의 동적 컴포넌트는 동적으로 컴포넌트를 전환할 수 있는 기능을 제공합니다. 하나의 컴포넌트 내에서 조건에 따라 다른 컴포넌트를 동적으로 렌더링하고자 할 때 매우 유용합니다. Vue의 component 태그를 사용하여 이를 구현할 수 있습니다.
component 태그의 is 속성을 사용해 렌더링할 컴포넌트를 지정합니다. is 속성의 값에 따라 다른 컴포넌트를 동적으로 렌더링합니다.
<template>
<div>
<!-- 동적 컴포넌트 -->
<component :is="currentComponent"></component>
<!-- 버튼을 클릭해 컴포넌트 변경 -->
<button @click="currentComponent = 'ComponentA'">Show Component A</button>
<button @click="currentComponent = 'ComponentB'">Show Component B</button>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
// 초기 렌더링할 컴포넌트
currentComponent: 'ComponentA'
};
}
};
</script>
component 태그 위치에 어떤 컴포넌트가 렌더링 될지가 반응형 데이터 값에 기반해 결정됩니다.
아래처럼 컴포넌트가 변경될 때 애니메이션을 적용할 수도 있습니다.
<template>
<div>
<transition name="fade">
<component :is="currentComponent"></component>
</transition>
<button @click="currentComponent = 'ComponentA'">Show Component A</button>
<button @click="currentComponent = 'ComponentB'">Show Component B</button>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentComponent: 'ComponentA'
};
},
components: {
ComponentA,
ComponentB
}
};
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>