v-if 를 사용하여 조건부 랜더링
✅ 장점
- Vue가 필요할 때만 해당 컴포넌트를 생성하므로 불필요한 랜더링이 없다.
🟧 단점
- 한 번 v-if로 렌더링을 제거하면 해당 컴포넌트의 상태도 사라지기 때문에 다시 렌더링하면 초기 상태로 돌아간다.
<script setup lang="ts">
import { ref } from 'vue'
import TestA from './components/TestComponentA.vue'
import TestB from './components/TestComponentB.vue'
const currentTab = ref<'A' | 'B'>('A')
// 버튼 클릭 시 컴포넌트 변경
const changeComponent = (tab: 'A' | 'B') => {
currentTab.value = tab
}
</script>
<template>
<div>
<button @click="changeComponent('A')">A 버튼</button>
<button @click="changeComponent('B')">B 버튼</button>
<TestA v-if="currentTab === 'A'" />
<TestB v-else-if="currentTab === 'B'" />
</div>
</template>
v-show를 사용하여 렌더링
✅ 장점
- v-show는 DOM에서 제거되지 않고, CSS display: none;으로 숨김 처리된다.
- 따라서 컴포넌트의 상태가 유지된다. (예: input 입력값 등이 남아있음)
🟧 단점
- 모든 컴포넌트가 한 번 렌더링되며, DOM에 계속 남아 있기 때문에 메모리 사용량이 증가할 수 있다.
<template>
<div>
<button @click="changeComponent('A')">A 버튼</button>
<button @click="changeComponent('B')">B 버튼</button>
<TestA v-show="currentTab === 'A'" />
<TestB v-show="currentTab === 'B'" />
</div>
</template>
component를 사용하여 렌더링
✅ 장점
- <component>는 동적 컴포넌트 또는 엘리먼트를 렌더링하기 위한 "메타 컴포넌트"이다.
- is라는 prop의 값으로 렌더링할 실제 컴포넌트가 결정되며 문자열인 경우, HTML 태그 이름 또는 컴포넌트로 등록된 이름일 수 있다.
- <component>를 그대로 활용하면서 불필요한 조건문을 없앨 수 있다.
- 컴포넌트의 상태를 유지한다.
https://ko.vuejs.org/api/built-in-special-elements.html#component
<script setup lang="ts">
import { shallowRef } from 'vue'
import TestA from './components/TestComponentA.vue'
import TestB from './components/TestComponentB.vue'
const currentTab = shallowRef<typeof AComp | typeof BComp>(AComp)
const components = {
TestA,
TestB,
}
// 버튼 클릭 시 컴포넌트 변경
const changeComponent = (key: keyof typeof components) => {
currentTab.value = components[key]
}
</script>
<template>
<div>
<button @click="changeComponent('TestA')">A 버튼</button>
<button @click="changeComponent('TestB')">B 버튼</button>
<component :is="currentTab"></component>
</div>
</template>
v-if & v-show & component 비교
방법 | 상태 유지 | 렌더링 성능 | 사용 추천 |
v-if | 컴포넌트 변경 시 초기화 | 빠름 (필요할 때만 렌더링) | 컴포넌트 변경 시 상태 유지가 필요 없을 때 |
v-show | 컴포넌트 변경 후에도 상태 유지 | 느림 (모든 컴포넌트가 유지됨) | UI 전환이 잦고, 컴포넌트 상태를 유지해야 하는 경우 |
component | 상태 유지 | 최적화됨 (불필요한 재렌더링 없음) | 컴포넌트 변경 시 상태를 유지하면서도 성능 최적화를 하고 싶을 때 |
'Vue.js' 카테고리의 다른 글
[Vue.js] computed & watch 차이점 (feat. watchEffect) (0) | 2025.02.12 |
---|---|
[Vue.js] v-for 사용시 key 값으로 index를 사용하지 않는 이유 (0) | 2025.02.07 |
[Vue.js] <script>가 <template>보다 위에 있어도 상관없을까? (1) | 2025.02.07 |