날아라김지원
article thumbnail
Published 2023. 4. 2. 13:11
Vue.js vue-rotuer, 라우팅하기 Vue.js

- vue-router

기본적인 프로젝트 주소에서 다른페이지로 라우팅 할때 쓰는 도구이다. 

 

사이트주소/detail, 사이트주소/detail/0, 사이트주소/mypage, 사이트주소/home

 

이런식으로 사용할 수 있다.

 

사용하기 위해선 설치먼저 해줘야한다.

npm install vue-router@4

https://router.vuejs.org/

 

Vue Router | The official Router for Vue.js

The official Router for Vue.js

router.vuejs.org

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

const routes = [
  {
    path: "/경로",
    component: 컴포넌트,
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

그리고 이와같이 src폴더에 router.js를 만들어 삽입 해준다. 그냥 사용법이니 사용법을 기억하면 된다.

 

main.js파일에도 이 두줄을 밑에 추가해준다.

import router from './router'
createApp(App).use(router).mount('#app')
import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import madeRouter from './router.js'
// router설정위함


// 라우터 설정 해줘야한다.
createApp(App).use(madeRouter).mount('#app')

위와같이 완성한다. use안의 이름은 마음대로 정할 수 있다.

 

그리고 router를 특정페이지 특정 위치에서 사용하기 위해 <router-view>를 추가해줘야한다.

 

App.vue에 특정 위치에서 보여주기 위해서 아래와 같이 설정했고, props도 router에 전송할 수 있다.

App.vue

.......
</nav>
<div>
  <router-link to="/">홈페이지</router-link>
  <router-link to="/ListPost">리스트페이지</router-link>
<router-view :blogPost="blogPost"></router-view>
<!-- <ListPost :blogPost="blogPost"></ListPost> -->

</div>
</div>

</template>

.........

그리고 라우팅된 페이지에서 또 router-view를 사용할 수 있다. (댓글기능, 추가 상세페이지 등)

DetailPage.vue

<template>
    <!-- $route.params -->
    <!-- 현재 URL의 정보는 $route에 담겨있다. -->
<div>    <h1>상세페이지</h1>
    <h5>{{ blogPost[$route.params.id].title }}</h5>
    <p>{{ blogPost[$route.params.id].content }}</p>
    <router-view></router-view>
    <!-- children안에 있는 페이지를 여기서 보여준다. -->
  </div>
</template>

- router.js에 여러 라우팅 페이지 추가하기 및 개념 정리

1)router추가하기

const routes = [
    {
        path: "/",
        component: HomePage,
    },
  {
    path: "/ListPost", // redirection (다른페이지로 이동시키는거 그런것도 가능)
    component: ListPost,
    // Named View사용하면 여기 {}형태로 여러 컴포넌트 넣을 수 도 있다. 문서 확인!
    // ListPost.vue로 잘못쳤다.
  },

2)URL 파라미터 만들기, Nested routes & push 사용하기

  {
    path:"/detail/:id",
    // path:"/detail/:id/:id2 이런식으로도 가능",
    // 파라미터 업그레이드 가능 숫자만 들어오게 그런식으로 (정규식 등등 공식문서 참고 vue-router-4)

    // :id 아무문자, URL :파라미터 문법
    component:DetailPage,
    children:[
      // 이렇게 만들고 어디서 보여줄지도 정해야한다 (Detail페이지에서)
     {
      path:"author",
      // /author 슬래쉬 빼줘야한다. 홈페이지 부터란 뜻
      component:AuthorPage,
      // .vue 꼭좀 없애자
     },
     {
      path:"comment",
      component:CommentPage,
     }

    ]
  },

 

 

3)컴포넌트에서 URL 파라미터에 있는 값 확인 하는법 $route.params.파라미터명

 

{{ $route.params.파라미터명 }} 같이 값을 받아서 사용할 수 있다.

<template>
    <!-- $route.params -->
    <!-- 현재 URL의 정보는 $route에 담겨있다. -->
<div>    <h1>상세페이지</h1>
    <h5>{{ blogPost[$route.params.id].title }}</h5>
    <p>{{ blogPost[$route.params.id].content }}</p>
    <router-view></router-view>
    <!-- children안에 있는 페이지를 여기서 보여준다. -->
  </div>
</template>

4)router-link 와 $router.push 사용하기 (페이지 이동 링크)

 

@click 이벤트에 $router.push를 아래와 같이 사용해 주소를 이동 할 수 도 있고

 

<router-link to=""> 를 사용해 이용할 수 도 수도 있다. router.push의 사용법에따라 1을 넣으면 앞으로 -1은 뒤로가기등

 

여러 구현이 가능하다. 그리고 변수 넣기도 좀더 쉽다. router-link의 경우 :와 `백틱을 사용해 줘야하는 번거로움도 있다.

 

      <!-- @click으로도 구현가능, $표시 매우 중요하다. -->
      <h5 @click="$router.push('/detail/0')">{{ post.title }}</h5>
      <!-- $router.go(1) 혹은 -1,-2입력에 따라 가는 사이트가 있다. 공식 사이트 확인하기 -->
      <!-- ps.$route.fullpath하면 현재 페이지 주소 알려준다. -->
      <!-- $router.push('/detail/0') -->
   <router-link to="/detail/">      <h5>{{ post.title }}</h5></router-link>
   <router-link :to="`/detail/${index}`" class="button">go path</router-link>
    
      <!-- https://velog.io/@mahns/vue-router-link -->

https://router.vuejs.org/

 

Vue Router | The official Router for Vue.js

The official Router for Vue.js

router.vuejs.org

필요에 따라 찾아가면서 학습하자.

 

- 그외 추가 개념

1)hash mode와 html모드

해시 모드의경우 #붙은채로 주소가 시작한다. #뒤의 내용은 서버로 전달되지 않는다.

 

2)Navigation guards

특정 URL로 접속할 때 실행하고 싶은 코드가 있을 때 사용한다 주로 로그인 검증 같은 경우에 사용하고

hook과 비슷하다고 보면 된다.

route.js에서 아래와 같이 사용한다. 필요할 때 추가로 찾아서 사용해보자

const routes = [
  {
    path: "/hello",
    component: HelloWorld,
    beforeEnter: (to, from)=>{
      return to.fullPath
    }
  }
];

또한 Vue컴포넌트 라이프사이클 훅 사용하는 곳에서도 비슷하게 실행하려면

beforeRouteEnter(){}
beforeRouteUpdate(){}

이 두개를 사용해 주면 비슷하게 쓸 수 있다. ajax요청같은곳에 사용한다.

profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!