[Vue.js] vue-router #3 - 중첩된 라우트

SOLEE_DEV·2021년 1월 9일
1

Vue.js

목록 보기
3/9
post-thumbnail

본 포스팅은, 뷰 라우터 공식 문서(https://router.vuejs.org/kr/guide/essentials/history-mode.html)와
'캡틴판교의 Cracking Vue.js' 내용에 기반하여 작성된 포스팅입니다.
자세한 내용은 공식 문서와 '캡틴판교의 Cracking Vue.js'를 참조해주세요!

중첩된 라우트

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

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

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

<div id="app">
  <router-view></router-view>
</div>
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

...

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

여기에 있는 router-view최상위 outlet으로, 최상위 경로와 일치하는 컴포넌트를 렌더링한다.
비슷하게 렌더링된 컴포넌트는 자신의 중첩된 router-view를 포함할 수도 있다.

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

...

const router = createRouter({
  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
        }
      ]
    }
  ]
})

이 중첩 outlet에 컴포넌트를 렌더링하려면 children를 사용해야 한다.

/로 시작하는 중첩 라우트는 루트 경로로 취급된다.
이렇게 하면 중첩된 URL을 사용하지 않고도 컴포넌트 중첩을 활용할 수 있다.

children옵션은 routes와 같은 라우트 설정 객체의 또 다른 배열이다. 따라서 필요한만큼 중첩된 뷰를 유지할 수 있다.

이 때, params로 넘어온 id값이 없을 때 기본으로 출력할 페이지를 렌더링하기 위해서는 빈 서브 루트 경로를 제공함으로써 구현해낼 수 있다.

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

        // ...또 다른 서브 라우트
      ]
    }
  ]
})
profile
Front-End Developer

0개의 댓글