// Vue Router 실행
$ vue create vue-router-app
$ cd vue-router-app
// 프로젝트 진행중 router를 추가하면 App.vue가 덮어써지기 때문에 유의
$ vue add router
http:.../index
http:...#index
router-link 추가
- a 태그와 비슷한 기능
- 목적 경로는 to
속성으로 지정
- routes에 등록된 component와 매핑됨
```html
<!-- App.vue -->
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</div>
</template>
```
```js
const routes = [
{
path: "/",
name: "home",
component: HomView
},
]
```
router-link의 to
속성으로 주소 전달
이름을 가지는 routes
- Django에서 path 함수의 name 인자의 활용과 같은 방식
```js
// router/index.js
const routes = [
{
path: "/",
name: "home",
component: HomeView
},
]
```
- 동적인 값을 사용하기 때문에 v-bind를 사용해야 정상적으로 작동
```html
<!-- App.vue -->
...,
<router-link :to="{ name: 'home' }">Home</router-link>
<router-link :to="{ name: 'about' }">About</router-link>
```
vue 인스턴스 내부에서 라우터 인스턴스에 $router
로 접근 할 수 있음
다른 URL로 이동하려면 this.$router.push
를 사용
- history stack에 이동할 URL을 넣는 방식
- 기록이 남기 때문에 뒤로가기 등의 기능 사용 가능
동작 원리는 선언적 방식과 같음
```html
<!-- somethingView.vue -->
<template>
<button @click="toHome">홈으로</button>
</template>
<script>
export default {
...,
methods: {
toHome() {
this.$router.push({ name: "home" })
}
}
}
</script>
```
View component 작성
<!-- views/HelloView.vue -->
<template>
</template>
<script>
export default {
name: "HelloView",
}
</script>
route 추가
// router/index.js
import HelloView from "@/views/HelloView"
const routes = [
...,
{
path: "/hello/:userName",
name: "hello",
component: HelloView
},
]
// router/index.js
const routes = [
{
path: "/about",
name: "about",
component: () => {
import("@/views/AboutView"),
}
}
]
router.beforeEach()
를 사용하여 설정to
: 이동할 URL 정보가 담긴 Route 객체from
: 현재 URL 정보가 담긴 Route 객체next
: 지정한 URL로 이동하기 위해 호출하는 함수, 콜백 함수 내에서 한 번만 호출 가능router.beforeEach()
가 호출됨next()
가 호출되면 라우팅이 일어남 #
- 라우터 가드: 특정 URL에서만 동작
- `beforeEnter()`
- route에 진입했을 때 실행됨
- 라우터를 등록한 위치에 추가
- 매개변수, 쿼리 등 값이 변경될 때는 실행되지 않고 다른 경로에서 탐색할 때만 실행됨
- 콜백 함수는 `to`, `from`, `next`를 인자로 받음
#
- 컴포넌트 가드: 라우터 컴포넌트 안에 정의
- `beforeRouteUpdate()`
- 해당 컴포넌트를 렌더링하는 경로가 변경될 때 실행
path: "*"
형태로 /404에 redirect를 시켜줌 ```js
.catch((error) => {
this.$router.push("/404")
})
```