FrameWorks/Vue

VueRouter의 Named View 파헤치기

ABCD 2024. 6. 23.

이름이 있는 뷰

때로는 여러 뷰(view)를 중첩하지 않고 동시에 표현해야 할 때가 있습니다.
이름이 지정되지 않은 <router-view>는 기본값으로 default를 가지게 됩니다.
하지만, 우리는 <router-view>name속성을 활용하여 원하는 컴포넌트를 추가해 고정시킬 수 있습니다.

const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
components: {
default: Home,
// 두 컴포넌트를 `<router-view>`의 `name` 속성에 매치 시킴
// key: value로 선언하지 않았지만 `LeftSidebar: LeftSidebar`로 선언된 것과 똑같이 동작
LeftSidebar,
RightSidebar,
},
},
],
})

중첩된 이름이 있는 뷰

중첩된 뷰와 이름이 있는 뷰를 사용하여 복잡한 레이아웃을 구성할 수 있습니다.
예를 들어보겠습니다.

/settings/emails /settings/profile
+-----------------------------------+ +------------------------------+
| UserSettings | | UserSettings |
| +-----+-------------------------+ | | +-----+--------------------+ |
| | Nav | UserEmailsSubscriptions | | +-----> | | Nav | UserProfile | |
| | +-------------------------+ | | | +--------------------+ |
| | | | | | | | UserProfilePreview | |
| +-----+-------------------------+ | | +-----+--------------------+ |
+-----------------------------------+ +------------------------------+
  • UserSettings: 부모 뷰로 렌더링된 컴포넌트
  • Nav: 일반 컴포넌트
  • UserEmailsSubscriptions: UserSettings 내에 중첩된 뷰 컴포넌트
  • UserProfile: UserSettings 내에 중첩된 뷰 컴포넌트
  • UserProfilePreview: UserSettings 내에 중첩된 뷰 컴포넌트

위 레이아웃(HTML/CSS로 만든 레아이웃은 잠시 잊고 생각해 보시죠.) <UserSettings /> 컴포넌트 템플릿은 다음과 같습니다.

<!-- UserSettings.vue -->
<div>
<h1>사용자 설정</h1>
<NavBar />
<router-view />
<router-view name="subView" />
</div>

 

이제 route를 어떻게 설정했는지 알아보죠.

const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/settings',
// 상단에 이름이 있는 view를 가질 수도 있음
component: UserSettings,
children: [
{
path: 'emails',
component: UserEmailsSubscriptions,
},
{
path: 'profile',
components: {
default: UserProfile,
subView: USerProfilePreview,
},
},
],
},
],
})
728x90
반응형

댓글