기술 정리/Vue

[Vue] 중첩된 라우트

Treejin 2021. 4. 24. 11:44
반응형

Vue를 활용해 개발을 하다보면, index/dashboard, index/myproject처럼 중첩해서 페이지를 보여주는 경우가 생긴다.

이런 경우 사용할 수 있는 것이 중첩된 라우트(nested router)이다.

 

중첩된 라우트는 router의 기능 중 children을 사용하여 구현할 수 있다.

 

router의 index.js

{
        path: "/index",
        name: "Index",
        component: Index,
        children: [
            {
                path: "dashboard",
                name: "DashBoard",
                component: DashBoard,
            },
            {
                path: "myproject",
                name: "MyProject",
                component: MyProject,
            },
        ]
}

App.vue

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

Index.vue

<template>
    <div>
        <navbar></navbar>
        <router-view id="main"></router-view>
    </div>
</template>

위와 같은 형태로 구현했을 때

  • index/dashboard로 조회하면, App.vue의 router-view에는 Index 컴포넌트가, 그리고 Index.vue의 router-view는 DashBoard컴포넌트가 배치된다.
  • index/myproject로 조회하면, App.vue의 router-view에는 Index 컴포넌트가, 그리고 Index.vue의 router-view는 MyProject컴포넌트가 배치된다.

이를 이용해 중첩된 라우터를 구현할 수 있고, 페이지를 변경할 때 공통된 부분은 통일하고 필요한 부분만 변경해서 활용할 수 있다!

반응형