$ vue create {프로젝트 이름} // Vue 프로젝트 생성
$ cd {프로젝트 이름(디렉토리 이름)} // 디렉토리 이동
$ vue add router // Vue CLI에서 router plugin 적용
Vue router를 추가하게 되면 history mode를 사용할 것인지 물어본다. 'yes'를 선택한다.

{프로젝트 이름}/src/에 router와 views 폴더가 추가된 것을 볼 수 있다.
아래 코드블록은 공식 문서에서 퍼온 것으로, router-link와 router-view의 기능과 사용법을 알 수 있다.
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- use the router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
router-link 태그는 src/router/index.js의 routes에 등록된 컴포넌트와 매핑된다.router-link는 클릭 이벤트를 차단하여 a 태그와 달리 페이지가 재렌더링 되지 않도록 한다. (새로고침 차단)to 속성 : 해당 router-link의 목표 경로router-view는 실제 컴포넌트가 렌더링되는 곳// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '@/views/HomeView'
// 경로와 컴포넌트가 매핑되는 곳
const routes = [
{
path: '/',
name: 'home',
component: HomeView
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
urls.py에 해당router-view에 들어갈 컴포넌트를 추가할 폴더src/commponents/폴더에 추가한다.// App.vue
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view/>
</div>
</template>
router-link의 to 속성으로 해당 태그를 클릭했을 때 이동할 주소를 전달// src/router/index.js
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
}
]
// App.vue
<template>
<div id="app">
<nav>
<router-link to="{ name: 'home' }">Home</router-link> |
<router-link to="{ name: 'about' }">About</router-link>
</nav>
<router-view/>
</div>
</template>
src/router/index.js에 routes를 선언할 때 지정해 준 이름을 router-link의 to속성에 객체로 전달// AboutView.vue
<template>
<div class="about">
<h1>This is an about page</h1>
// 클릭하면 home으로 이동
<button @click="toHome">Home</button>
</div>
</template>
<script>
export default {
name: 'AboutView',
methods: {
toHome() {
this.$router.push({ name: 'home'})
}
}
}
</script>
$router로 접근this.$router.push를 사용하여 다른 URL로 이동
<router-link :to="..."를 클릭하는것과$router.push(...)호출하는 것은 같은 동작!