단일 페이지 어플리케이션(SPA) 인 vue 프로젝트에서의 링크 및 라우팅은 Vue.js 의 공식 라우터인 Vue Router 를 사용할 수 있다. (써드파티 라우터도 상관없음. Page.js, Director, ...) 이 때 라우터는 화면 전환에 필요한 기능들을 제공한다. 경로 매핑, 전환 효과... 우리는 단지 컴포넌트(.vue) 를 열심히 만들어 경로에 매핑하면 된다. 만약 단순한 라우팅만 필요하다면 별도의 라이브러리 없이 페이지 수준의 컴포넌트를 렌더링 하면 된다.
설치
> npm install vue-router
# or
> npm install vue-router@4
1. src/router.js
이 파일에 라우팅 경로와 매핑될 컴포넌트 정보들을 작성한다.
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
import Component1 from "@/components/Component1";
import Component2 from "@/components/Component2";
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/',
component: App
},
{
path: '/menu1',
component: Component1
},
{
path: '/menu2',
component: Component2,
children: [
...
}
}
],
mode: 'history'
})
export default router
가장 쉬운 방법으로 path 에 매칭되는 컴포넌트를 정의하였으며, children 안에는 동일하게 서브 path 와 컴포넌트들을 정의할 수 있다. vue-router 의 기본 mode 는 hash 이며 url 에 해시(#)가 추가되는데, 해시를 제거하려면 history 모드를 사용해야 한다.
2. src/main.js
Vue 인스턴스에 라우터 추가
import router from './router'
new Vue({
render: h => h(App),
router // routes: routes 의 줄임
}).$mount('#app')
3. component.vue
<template> 안에서는 선언적 방식의 router 관련 태그로 <router-link> 와 <router-view> 가 주로 사용된다. <router-link> 는 <a> 태그로 렌더링되며, <router-view> 자리에는 지정된 컴포넌트가 렌더링된다.
<router-link to="/menu1">/menu1</router-link>
<router-link to="/menu2">/menu2</router-link>
<router-view name="navigation"></router-view>
<router-view name="contents"></router-view>
<router-link> 를 사용하면, url 에 매칭되었을 때 해당 태그에 'router-link-active' 클래스가 생성되므로 원한다면 스타일도 쉽게 적용 가능하다.
라우터 파라미터
routes: [
{ path: '/user/:id', component: User },
{ path: '/user/:id', component: User, props: true },
{ path: '/user', component: User, props: (route) => ({ query: route.query.q }) },
]
- 첫번째 예는 컴포넌트에서 $route.params.id 로 속성을 받을 수 있다.
- 두번째 예는 컴포넌트 옵션에서 props: ['id'] 로 선언 후 id 로 속성을 받을 수 있다.
- 세번째 예는 /user?q=abc 에 대해 props: ['query'] 로 선언 후 속성을 받을 수 있다.
프로그래밍 방식의 router 사용
주로 Vue 인스턴스 내부에서 프로그래밍 방식(this.$router)으로 사용하여 라우터 인스턴스 메소드를 사용할 수 있다.
this.$router.push(path) // window.history.pushState
this.$router.replace(path) // window.history.replaceState
this.$router.go(-1) // window.history.go(-1)
WRITTEN BY
- 손가락귀신
정신 못차리면, 벌 받는다.