본문 바로가기
Dev/✅ Vue.js

vue-router 설치부터 환경설정 및 사용방법

by 아아덕후 2023. 5. 2.
반응형

 

 

목차

1. router 설치
2. router 설정
3. router 예제

 


1. router 설치 (yarn , npm) 

yarn 설치

yarn add vue-router@4

 

npm 설치

npm install vue-router@4

 

 

참고 :  https://router.vuejs.org/installation.html

 

 


2. router 설정

router를 사용하기 위해 3개 의 파일을 설정해야 합니다.

3개의 파일은 router-index.js / main.js  / App.vue 입니다. 

 

index.js

첫 번째로, router 폴더를 생성하고 그 안에 index.js 생성해야 합니다.

해당 폴더는 밑에 main.js에서 호출하여 전역으로 router로 사용하기 위한 설정을 위한 폴더입니다.

왜냐하면 index.js를 src 바로 아래 레벨에서 관리하게 되면 개발 중 오해 혹은 실수가 발생할 수 있기 때문이라고 생각합니다.

src 폴더 내에 components 폴더와 같은 레벨에 router 폴더를 생성한 후  index.js 파일을 생성합니다.

프로젝트 폴더    
   ├─── node_modules   
   ├─── ...   
   └─── src         
               ├─── assets         
               ├─── ...         
               ├─── components         
               └─── router                 
                           └─── index.js

 

이후 index.js에서 vue-router를 호출하고 

// router/index.js

import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(""),
  routes: [
    {
      path: "/",
      name: "main",
      component: () => import("../components/main.vue"),
    },
    {
      path: "/test",
      name: "test",
      component: () => import("../components/test.vue"),
    },
  ],
});

export default router;

 

 

main.js

두 번째로 router를 전역으로 사용하기 위해 main.js에서 위에서 설치한 router를 호출합니다.

이후 createApp(App) 인스턴스 뒤에 .use(router)를 메서드 체이닝으로 router를 추가합니다.

// main.js

import { createApp } from "vue";
import App from "./App.vue";

// 라우터
import router from "./router";

createApp(App).use(router).mount("#app");

App.vue

세 번째로 App.vue (혹은 기준이 되는 컴포넌트 파일)에서 router-view를 선언해 줍니다.

 

 

 

// App.vue

<script></script>

<template>
  // <header/>
  <router-view> </router-view>
  // <footer/>
</template>

<style></style>

위와 같이 선언 후 첫 번째(index.js)에서 선언 한 컴포넌트들이 url 변경에 따라 

router-view 태그 내에서 호출이 되며 router에 따른 컴포넌트를 호출할 수 있습니다.

 

 


3. router 예제

프로젝트 폴더    
   ├─── node_modules   
   ├─── ...   
   └─── src         
               ├─── assets         
               ├─── ...         
               ├─── components     
               │          ├─── main.vue
               │          └─── test.vue  
               └─── router                 
                           └─── index.js

위와 같은 폴더 구조를 기반으로 router를 사용한 예시입니다.

 

main.vue 

main.vue 화면 , url : "/"

// main.vue

<script>
export default {
  methods: {
    onClickMoveTestPage() {
      this.$router.push('/test')
    }
  }
}
</script>

<template>
  <div>
    <h1>main Page</h1>
  </div>
  <button type="button" @click="onClickMoveTestPage">페이지 이동</button>
</template>

<style></style>

해당 페이지 이동 버튼 클릭 시, test 페이지로 이동하는 router 함수를 실행시켜 url이 변경됨과 동시에 컴포넌트도 변경됩니다.

 

test.vue 

 

 

test.vue 페이지 , url : "/test"

// test.vue


<template>
  <h2 class="boxTest">test 페이지</h2>
  <router-link to="/">메인페이지 이동</router-link>
</template>

<script>
export default {};
</script>

<style>
.boxTest {
  width: 200px;
  height: 50px;
  text-align: center;
  border: 1px solid #000;
}
</style>

 

url이 /test로 변경함에 따라 해당 url에 설정해 놓은 컴포넌트인 test.vue 컴포넌트를 실행합니다.

main.vue에서 사용한 것과 같이 함수를 사용하여 url 변경도 되며 

위 test.vue의 template 부분의 router-link 태그를 통해서도 url 이동이 가능합니다.

 

 


궁금하신 점이 있으시면 댓글로 남겨주세요.

 

감사합니다! 

 

 

참고 : https://router.vuejs.org/ 

 

Vue Router | The official Router for Vue.js

The official Router for Vue.js

router.vuejs.org

 

반응형

댓글