> For the complete documentation index, see [llms.txt](https://docs.sysout.co.kr/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sysout.co.kr/web/develop-page/js/vuejs/vue-cli-3/vue-router-4.md).

# Vue Router 4

## Vue Router 4

이 문서에서는 Vue-cli 3 프로젝트에 Vue Router 4를 추가하는 방법에 대해서 다룬다.

{% embed url="<https://router.vuejs.org/>" %}

### Vue Router란

Vue의 공식 라우터로 주소에 따라 다른 화면이 보일 수 있도록 처리하는 도구이다. SPA를 구축하기 위해 프론트엔드에서 주소를 인식하고 처리할 수 있도록 모든 작업을 지원한다.

{% embed url="<https://router.vuejs.org/introduction.html>" %}

### 의존성 설치

{% embed url="<https://www.npmjs.com/package/vue-router/v/next>" %}

#### npm

```bash
npm install vue-router@4
```

#### yarn

```bash
yarn add vue-router@4
```

### Vue Router 설정 파일

설정 파일은 어디에 두어도 상관없으나 대형 프로젝트에서 관리 편의를 위해 각자 기능에 맞게 폴더를 만들고 `index.js` 파일에 작성한다.&#x20;

{% hint style="info" %}

#### `파일 이름을 index.js로 작성하는 이유`

import에서 해당 파일 이름을 생략할 수 있다. 다음 둘은 같은 코드이다.

```javascript
import router from "./router";
import router from "./router/index.js";
```

{% endhint %}

{% code title="/src/router/index.js" %}

```javascript
import {createWebHashHistory, createRouter} from 'vue-router';

const router = createRouter({
    history:createWebHashHistory(),
    routes:[]
});

export default router;
```

{% endcode %}

Vue-router 설정을 main.js 파일로 불러와서 Vue Application에 등록 처리한다.

{% code title="/src/main.js" %}

```javascript
import { createApp } from 'vue'
import App from './App.vue'

//router 설정 불러오기
import router from "./router";

createApp(App)
    .use(router)//router 사용 설정
    .mount('#app')

```

{% endcode %}

Vue Router를 사용하기 위한 기본 준비는 마쳤다. 이제 화면을 만들면서 본격적인 라우팅이 이루어질 수 있도록 추가하는 작업이 남아있다.

### Routing Component 구현

`/src/components` 안에 다음 두 개의 파일을 생성한다.&#x20;

* /src/components/FirstScreen.vue
* /src/components/SecondScreen.vue

{% hint style="info" %}

#### Tip

파일 이름은 multi-word 형태로 작성해야 한다.
{% endhint %}

<details>

<summary>FirstScreen.vue</summary>

```markup
<template>
    <div>
        <h1>First Screen</h1>
    </div>
</template>
<script>
    export default {
        name:"FirstScreen"
    }
</script>
<style scoped>

</style>
```

</details>

<details>

<summary>SecondScreen.vue</summary>

```markup
<template>
    <div>
        <h1>Second Screen</h1>
    </div>
</template>
<script>
    export default {
        name:"SecondScreen"
    }
</script>
<style scoped>

</style>
```

</details>

각 파일의 내용은 구분을 위해 화면에 표시되는 글자와 이름을 다르게 설정하였다. 이 컴포넌트들을 Vue Router에 등록한다.

{% code title="/src/router/index.js" %}

```javascript
import {createWebHashHistory, createRouter} from 'vue-router';

//주소와 연결할 컴포넌트를 불러온다
import FirstScreenVue from "@/components/FirstScreen.vue";
import SecondScreenVue from "@/components/SecondScreen.vue";

const router = createRouter({
    history:createWebHashHistory(),
    routes:[
        //기본 주소(/) 요청이 올 경우 FirstScreenVue로 연결한다
        {path:"/first", component:FirstScreenVue},
        //second 주소 요청이 올 경우 SecondScreenVue로 연결한다
        {path:"/second", component:SecondScreenVue},
    ]
});

export default router;
```

{% endcode %}

<mark style="color:red;">import</mark> 키워드로 만들어진 Vue Component를 불러오고, <mark style="color:red;">routes</mark> 내부에 객체 형태로 경로(path)와 컴포넌트(component)를 설정하면 기본 라우팅 설정이 완료된다.

{% hint style="info" %}

#### routes 설정 시 주의사항

애플리케이션이 최초로 실행되면 기본 주소인 `/` 화면이 불러지므로 `/` 에 대한 routes 설정은 반드시 필요하다.
{% endhint %}

### Router View 생성

최초 생성 시 만들어져 있던 HelloWorld.vue 파일을 제거한다.

* /src/components/HelloWorld.vue

App.vue의 내용을 다음과 같이 작성한다.

{% code title="/src/App.vue" %}

```xml
<template>
  <img alt="Vue logo" src="@/assets/logo.png">

  <hr>
  
  <router-link to="/">first screen</router-link>
  &nbsp;&nbsp;&nbsp;
  <router-link to="/second">second screen</router-link>

  <hr>

  <router-view></router-view>
</template>

<script>
export default {
  name: 'App',
  components: {
    
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

```

{% endcode %}

<mark style="color:red;">`<router-link>`</mark>는 Vue router에게 요청을 전달할 수 있는 링크이다. <mark style="color:red;">`<router-view>`</mark> 는 현재 주소에 따라 Vue router에서 제공하는 컴포넌트가 출력될 영역이다. 따라서 <mark style="color:red;">`<router-link>`</mark> 를 누르면 <mark style="color:red;">`<router-view>`</mark>의 화면이 변경되는 것을 확인할 수 있다.

### 실행 결과

<div align="left"><img src="/files/JJU1my3RBxFfkY4BArWD" alt=""></div>
