Skip to content

이름 있는 뷰

때로는 뷰를 중첩하는 대신 여러 뷰를 동시에 표시해야 할 때가 있습니다. 예를 들어 sidebar 뷰와 main 뷰가 있는 레이아웃을 만들 때 그렇습니다. 이럴 때 이름 있는 뷰가 유용합니다. 뷰에 하나의 outlet만 두는 대신 여러 개를 둘 수 있고 각각에 이름을 붙일 수 있습니다. 이름이 없는 router-view에는 default라는 이름이 부여됩니다.

template
<router-view class="view left-sidebar" name="LeftSidebar" />
<router-view class="view main-content" />
<router-view class="view right-sidebar" name="RightSidebar" />

뷰는 컴포넌트를 사용해 렌더링되므로, 여러 뷰를 사용하려면 같은 라우트에 대해 여러 컴포넌트가 필요합니다. components(끝에 s가 있음) 옵션을 사용해야 한다는 점에 유의하세요:

js
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      components: {
        default: Home,
        // LeftSidebar: LeftSidebar의 축약형
        LeftSidebar,
        // `<router-view>`의 `name` 속성과 일치합니다
        RightSidebar,
      },
    },
  ],
})

이 예제의 동작하는 데모는 여기에서 확인할 수 있습니다.

중첩된 이름 있는 뷰

중첩된 뷰와 함께 이름 있는 뷰를 사용하면 복잡한 레이아웃을 만들 수 있습니다. 이 경우 중첩된 router-view에도 이름을 부여해야 합니다. 설정 패널 예제를 살펴봅시다:

/settings/emails                                       /settings/profile
+-----------------------------------+                  +------------------------------+
| UserSettings                      |                  | UserSettings                 |
| +-----+-------------------------+ |                  | +-----+--------------------+ |
| | Nav | UserEmailsSubscriptions | |  +------------>  | | Nav | UserProfile        | |
| |     +-------------------------+ |                  | |     +--------------------+ |
| |     |                         | |                  | |     | UserProfilePreview | |
| +-----+-------------------------+ |                  | +-----+--------------------+ |
+-----------------------------------+                  +------------------------------+
  • Nav는 일반 컴포넌트입니다
  • UserSettings는 부모 뷰 컴포넌트입니다
  • UserEmailsSubscriptions, UserProfile, UserProfilePreview는 중첩된 뷰 컴포넌트입니다

참고: 이런 레이아웃을 표현하기 위한 HTML/CSS 모양은 잠시 잊고, 사용되는 컴포넌트에만 집중합시다.

위 레이아웃에서 UserSettings 컴포넌트의 <template> 섹션은 대략 다음과 같습니다:

template
<div>
  <h1>User Settings</h1>
  <NavBar />
  <router-view />
  <router-view name="helper" />
</div>

그 다음 다음과 같은 라우트 구성을 사용해 위 레이아웃을 구현할 수 있습니다:

js
{
  path: '/settings',
  // 상위 레벨에도 이름 있는 뷰를 둘 수 있습니다
  component: UserSettings,
  children: [
    {
      path: 'emails',
      component: UserEmailsSubscriptions
    },
    {
      path: 'profile',
      components: {
        default: UserProfile,
        helper: UserProfilePreview
      }
    }
  ]
}

이 예제의 동작하는 데모는 여기에서 확인할 수 있습니다.

모두를 위한 문서 한글화