[Vue3] 동적 컴포넌트

Dohee Kang·2023년 3월 4일
0

Vue

목록 보기
15/28

탭 인터페이스와 같이 컴포넌트 간에 동적으로 전환하는 것이 유용한 경우가 있다.
<component> 엘리먼트를 통해 동적으로 컴포넌트를 생성할 수 있는데 아래 예제를 통해 확인해보자.

  • App.vue(부모 컴포넌트)에 아래와 같이 작성한다.
<template>
  <div class="demo">
  </div>
</template>

<script>
import FirstComponent from './components/FirstComponent.vue'
import SecondComponent from './components/SecondComponent.vue'
import ThirdComponent from './components/ThirdComponent.vue'
  
export default {
  components: {
    FirstComponent,
    SecondComponent,
    ThirdComponent
  },
  data() {
    return {
      currentTab: 'FirstComponent',
      tabs: ['FirstComponent', 'SecondComponent', 'ThirdComponent']
    }
  }
}
</script>

<style>
.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}

.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.tab-button:hover {
  background: #e0e0e0;
}
.tab-button.active {
  background: #e0e0e0;
}
.tab {
  border: 1px solid #ccc;
  padding: 10px;
}
</style>
  • src/components 폴더 안에 컴포넌트 파일을 아래와 같이 생성하고 <template>을 작성한다.
<!-- FirstComponent.vue -->
<template>
  <div class="tab">
    First Component
  </div>
</template>

<!-- SecondComponent.vue -->
<template>
  <div class="tab">
    Second Component
  </div>
</template>

<!-- ThirdComponent.vue -->
<template>
  <div class="tab">
    Third Component
  </div>
</template>
  • 부모 컴포넌트에서 v-for 디렉티브를 통해 tabs의 길이만큼 <button>엘리먼트를 생성한다.
    • :class="['tab-button', { active: currentTab === tab }]"
      • 배열을 통해 class를 여러개 지정할 수 있다.
      • currentTabtab이 일치하면 active 클래스를 추가한다.
    • @click="currentTab = tab"
      • 버튼을 클릭하면 tab값이 currentTab에 저장한다.
<!-- App.vue -->
<template>
  <div class="demo">
    <button
      v-for="tab in tabs"
      :key="tab.index"
      :class="['tab-button', { active: currentTab === tab }]"
      @click="currentTab = tab"
    >
      {{ tab }}
    </button>
  </div>
</template>
  • <component> 엘리먼트를 통해 동적으로 컴포넌트를 전환한다.
    • :is="currentTab"
      • 버튼을 클릭할 때마다 변환되는 currentTab값이 :is를 통해 컴포넌트를 전환한다.
      • :is : 등록된 컴포넌트명의 문자열이나 실제 가져온 컴포넌트 객체를 작성한다.
    • class="tab"
      • class 속성을 통해 부모 컴포넌트 <style>에 정의되어 있는 tab 클래스를 자식 컴포넌트로 전달한다.
<!-- App.vue -->
<template>
  <div class="demo">
    ...
    <component :is="currentTab" class="tab" />
  </div>
</template>
  • 버튼을 클릭할 때마다 컴포넌트가 바뀌는 것을 알 수 있다.
profile
오늘은 나에게 어떤 일이 생길까 ✨

0개의 댓글