Home vue-router3 사용
Post
Cancel

vue-router3 사용

설치

1
npm install vue-router@3

vue-router 4가 나와서 이전 3와 설정방법이 다르다. 해당글은 vue-router 3를 사용한다.

게시판 화면 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- ./components/board/List.vue -->
<template>
  <div>게시판목록</div>
</template>

<!-- ./components/board/Form.vue -->
<template>
  <div>게시판폼</div>
</template>

<!-- ./components/board/View.vue -->
<template>
  <div>게시판상세</div>
</template>

설정(일반적인 방법)

./routers/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
    {
        path: '/board/list'
        component: () => import('./components/board/List')
    },
    {
        path: '/board/form'
        component: () => import('./components/board/Form')
    },
    {
        path: '/board/:id'
        component: () => import('./components/board/View')
    },
];

export default new VueRouter({
    scrollBehavior() {
        return { x: 0, y: 0 };
    },
    mode: 'history',
    routes
});

설정(도메인별로 모듈화)

./routers/board.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export default [
  {
    path: "/board/list",
    component: () => import("../components/board/List"),
  },
  {
    path: "/board/form",
    component: () => import("../components/board/Form"),
  },
  {
    path: "/board/:id",
    component: () => import("../components/board/View"),
  },
];

./routers/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Vue from "vue";
import VueRouter from "vue-router";
import board from "./board";

Vue.use(VueRouter);

const routes = [...board];

export default new VueRouter({
  /**
   * 라우팅 후 이전화면의 스크롤 위치가 그대로 유지되는데 이를 최상단으로 올려준다.
   */
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
  mode: "history",
  routes,
});

설정(모듈별 중첩)

./routers/board.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export default [
  {
    path: "/board",
    component: () => import("../components/Blank"),
    children: [
      {
        path: "list",
        component: () => import("../components/board/List"),
      },
      {
        path: "form",
        component: () => import("../components/board/Form"),
      },
      {
        path: ":id",
        component: () => import("../components/board/View"),
      },
    ],
  },
];

중첩된 라우팅을 사용할 경우엔 부모가 되는 path가 /board가 되는 부분에 <router-view />가 포함된 부모 컴포넌트가있어야한다. 위 코드에는 Blank.vue를 하나 만들어뒀다.

./components/Blank.vue

1
2
3
<template>
  <router-view />
</template>

라우터 등록

./main.js

1
2
3
4
5
6
7
8
9
10
import Vue from "vue";
import App from "./App.vue";
import router from "./routers";

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");
This post is licensed under CC BY 4.0 by the author.