Vue - dynamic component
Vue 를 사용하다보면 종종 컴포넌트를 바꾸고 싶을 때나 바꿔야 될 때가 있다. 근데 이게 router 를 거쳐서 이동되는 그런 사항은 아닌 경우가 있다.
그럴 경우 사용하게 되는 게 dynamic component 이다.
Dynamic Component
공식 문서에서는 아래와 같은 사용법을 안내하고 있다.
<component :is="currentTabComponent"></component>
해당 영역이 캐싱되길 원한다면 keep-alive 를 사용하면 된다. 다만 위와 같은 식으로 작성하게 될 경우 해당 페이지에 원하는 종류의 모든 컴포넌트를 import 해야할 수 있다.
그렇담?
원글: https://medium.com/scrumpy/dynamic-component-templates-with-vue-js-d9236ab183bb
번역 및 참조글: https://ui.toast.com/weekly-pick/ko_20180814
아래와 같이 작성하는 방식으로 회피할 수 있다! ✨
<template>
<component :is="component" :data="data" v-if="component" />
</template>
<script>
export default {
name: "dynamic-link",
props: {
data: {
type: Object,
required: true,
},
type: {
type: String,
required: true,
},
},
data() {
return {
component: null,
};
},
computed: {
loader() {
if (!this.type) {
return null;
}
return () => import(`./input/${this.type}`);
},
},
async mounted() {
try {
this.component = await this.loader;
} catch (error) {
alert(error);
}
},
};
</script>