[Vue] nested router

C____JIN·2022년 11월 9일
0

Vue

목록 보기
1/6
post-thumbnail

초기 버전

router/index.js

const routes = [
    {
        path: '/',
        name: 'PageHome',
        component: PageHome
    },
    {
        path: '/board',
        name: 'BoardList',
        component: BoardList
    },
    {
        path: '/detail',
        name: 'BoardDetail',
        component: BoardDetail
    },
    {
        path: '/write',
        name: 'BoardWrite',
        component: BoardWrite
    },
]
  • BoardList, BoardDetail, BoardWrite는 모두 게시판에 관한 기능이므로 공통 url을 /board로 묶어야겠다고 생각했다.

삽질1

router/index.js

const routes = [
    {
        path: '/',
        name: 'PageHome',
        component: PageHome,
    },
    {
        path: '/board',
        name: 'board',
        component: BoardList,
        children: [
            {
                path: "write",
                component: BoardWrite,
                name: 'BoardWrite',
            },
            {
                path: "detail",
                component: BoardDetail,
                name: 'BoardDetail',
            }
        ]
    },
]
  • 이렇게 구성을 했더니, /board에서 /detail, /write 페이지로 넘어가지 않고, 페이지가 멈춰있는 문제가 발생했다.

해결

children을 사용하는 경우는 크게 2가지가 있다.

  1. 공통 컨포넌트가 존재하는 경우에 공통 컨포넌트에서 <router-view></router-view> 태그를 사용해서 API 요청을 통해 태그에 해당하는 영역을 바꿀 때
  2. 별개의 컨포넌트들을 공통 url을 사용하여 가지 뻗어나갈 때 (v - 원했던 방식)

router/index.js

import { RouterView } from 'vue-router'

const routes = [
    {
        path: '/',
        name: 'PageHome',
        component: PageHome,
    },
    {
        path: '/board',
        name: 'board',
        component: RouterView,
        children: [
            {
                path: "write",
                component: BoardWrite,
                name: 'BoardWrite',
            },
            {
                path: "detail",
                component: BoardDetail,
                name: 'BoardDetail',
            },
            {
                path: "list",
                component: BoardList,
                name: 'BoardList',
            }
        ]
    },
]
  • 2번 방식으로 진행하기 위해서는 위 처럼 vue-router에서 import한 RouterView를 컨포넌트로 설정하고 List, Detail, Write를 모두 /board에서부터 뻗어져 나오게 하면 된다!
    • http://xxxxxx/board/write -> BoardWrite
    • http://xxxxxx/board/detail -> BoardDetail
    • http://xxxxxx/board/list -> Boardlist
profile
개발 블로그🌐 개발일지💻

0개의 댓글