Vue-router 중첩된 라우트

YEZI🎐·2022년 12월 8일
0

Vue

목록 보기
27/45

중첩된 라우트

실제 앱 UI는 일반적으로 여러 단계로 중첩된 컴포넌트로 이루어져 있다.
URL의 세그먼트가 중첩된 컴포넌트의 특정 구조와 일치한다는 것은 매우 일반적이다.

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

vue-router를 사용하면 중첩 된 라우트 구성을 사용하여이 관계를 표현하는 것이 매우 간단하다.

사용법

<router-view>는 최상위 outlet이다. 최상위 경로와 일치하는 컴포넌트를 렌더링한다.

<div id="app">
  <router-view></router-view>
</div>

라우터 컴포넌트 안에 하위 라우터 컴포넌트 <router-view>를 중첩하여 구성할 수 있다.

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

이 중첩 컴포넌트를 렌더링하려면 라우터 설정에서 children 옵션(Parent - Child 형태)을 사용해야한다.
/로 시작하는 중첩 된 라우트는 루트 경로로 취급된다. 이렇게하면 중첩된 URL을 사용하지 않고도 컴포넌트 중첩을 활용할 수 있다.

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // /user/:id/profile 과 일치 할 때
          // UserProfile은 User의 <router-view> 내에 렌더링
          path: 'profile',
          component: UserProfile
        },
        {
          // /user/:id/posts 과 일치 할 때
          // UserPosts가 User의 <router-view> 내에 렌더링
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

++ 빈 서브 루트 경로도 제공 할 수 있다.

const router = new VueRouter({
  routes: [
    {
      path: '/user/:id', component: User,
      children: [
        // UserHome은 /user/:id 가 일치 할 때
        // User의 <router-view> 안에 렌더링됩니다.
        { path: '', component: UserHome },

        // ...또 다른 서브 라우트
      ]
    }
  ]
})
profile
까먹지마도토도토잠보🐘

0개의 댓글