danbibibi
article thumbnail
Published 2023. 5. 14. 03:08
[Vue 기초 6] router WEB/front-end

1. vue-router

  • 라우팅 : 웹 페이지 간의 이동 방법
  • Vue.js의 공식 라우터
  • 라우터는 컴포넌트와 매핑
  • Vue를 이용한 SPA(Single Page Application)을 제작할 때 유용
  • URL에 따라 컴포넌트를 연결하고 설정된 컴포넌트를 보여줌

https://v3.router.vuejs.org/

Vue Router

v3.router.vuejs.org

 

2. vue-router 설치

2.1. CDN 방식

<html />
<script src="/path/to/vue.js"></script> <script src="/path/to/vue-router.js"></script>

 

2.2. NPM 방식

<bash />
npm install vue-router

 

3. vue-router 연결

routes 옵션과 함께 router instance 생성

<html />
<!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-8" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <title>Vue.js</title>     <style>       .router-link-exact-active {         color: red;       }     </style>     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>     <script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.js"></script>   </head>   <body>     <div id="app">       <h1>Router 실습r</h1>       <p>         <router-link to="/">메인</router-link>         <router-link to="/board">자유게시판</router-link>         <router-link to="qna/">질문게시판</router-link>         <router-link to="/gallery">사진게시판</router-link>       </p>       <!-- 현재 라우트에 맞는 컴포넌트가 렌더링 -->       <router-view></router-view>     </div>     <script>       // 라우트 컴포넌트       const Main = {         template: "<div>메인 페이지</div>",       };       const Board = {         template: "<div>자유 게시판</div>",       };       const QnA = {         template: "<div>질문 게시판</div>",       };       const Gallery = {         template: "<div>갤러리 게시판</div>",       };       // 라우터 객체 생성       const router = new VueRouter({         routes: [           {             path: "/",             component: Main,           },           {             path: "/board",             component: Board,           },           {             path: "/qna",             component: QnA,           },           {             path: "/gallery",             component: Gallery,           },         ],       });       // Vue 인스턴트 라우터 주입       const app = new Vue({         el: "#app",         router,       });     </script>   </body> </html>

 

4. vue-router 이동 및 렌더링

  • 네비게이션을 위해 router-link 컴포넌트를 사용
  • 속성은 to prop을 사용
  • 기본적으로 router-link는 <a> 태그로 렌더링
<html />
<router-link to="/">HOME</router-link> <router-link to="/board">게시판</router-link> <!-- 현재 라우트에 맞는 컴포넌트 렌더링 --> <router-view></router-view>

 

5. route 이름 설정

name 에 이름 설정

<javascript />
// 라우트 컴포넌트 import Main from './components/Main.js'; import Board from './components/Board.js'; import BoardView from './components/BoardView.js'; // 라우터 객체 생성 const router = new VueRouter({ routes: [ { path: '/', name: 'main', component: Main, }, { path: '/board', name: 'board', component: Board, }, { path: '/board/:no', name: 'boardview', component: BoardView, }, ], }); // Vue 인스턴트 라우터 주입 const app = new Vue({ el: '#app', router, });

 
다음과 같이 이름으로 매핑 가능하다!

<html />
<p> <router-link :to="{name: 'main'}">HOME</router-link> <router-link :to="{name: 'board'}">게시판</router-link> </p>

 

6. $rotuer, $route

<javascript />
// 전체 라우터 정보 this.$rotuer this.$router.push('/about'); // 새로운 URL로 이동하는 메소드 // 현재 호출된 해당 라우터 정보 this.$route this.$rotue.params.no this.$rotue.path
query vs parmas
query
- JSON 형태이며 query string 형태로 전달되는 파라미터 ex) https://example.com/user?name=john&age=30
- 주소 바깥 " ? " 이후의 변수 (여러개인 경우 &로 연결)
- $route.query로 접근

params
- name 형태에서 파라미터를 전달할때 사용 ex) https://example.com/user/22
- 주소에 포함된 변수
- $router.params로 접근

* query 와 params는 예약어 !! (임의로 변경하여 사용 불가)

 
Board.js

<javascript />
export default { template: `<div> 자유 게시판 <ul> <li v-for="i in 5"> <a :href="'#' + i" @click="$router.push({name: 'boardview', params: {no: i}})">{{i}}번 게시글</a> </li> </ul> </div>`, };

 
BoardView.js

<javascript />
export default { template: `<div> {{no}}번 게시물 상세정보 <a href="#board" @click="$router.push('/board')">게시판</a> </div>`, data() { return { no: 0, }; }, created() { console.dir(this.$route); // 현재 호출된 해당 라우터 정보 this.no = this.$route.params.no; }, };

 
Index.html

<html />
<p> <a href="#main" @click="$router.push('/')">HOME</a> <a href="#board" @click="$router.push('/board')">게시판</a> <a href="#qna" @click="$router.push({name: 'qna'})">QnA</a> <a href="#gallery" @click="$router.push({name: 'gallery'})">갤러리</a> </p>

 

7. route 중첩

children 내
create 로 작성하는 경우 /book/create 로 연결
/create 로 작성하는 경우 /create 로 연결 *부모 경로 고려 x
<javascript />
import Vue from 'vue' import VueRouter from 'vue-router' import HomeView from '@/views/HomeView.vue' import BookView from '@/views/BookView.vue' Vue.use(VueRouter) const routes = [   {     path: '/',     name: 'HomeView',     component: HomeView   },   {     path: '/book',     name: 'BookView',     component: BookView,     redirect: '/book/list',     children: [       {         path: 'list',         name: 'BookList',         component: () => import('@/components/book/BookList.vue')       },       {         path: 'create',         name: 'BookCreate',         component: () => import('@/components/book/BookCreate.vue')       },       {         path: 'detail/:isbn',         name: 'BookDetail',         component: () => import('@/components/book/BookDetail.vue')       },       {         path: 'modify/:isbn',         name: 'BookModify',         component: () => import('@/components/book/BookModify.vue')       },     ]   },   {     path: '/about',     name: 'AboutView',     component: () => import('@/views/AboutView.vue')   }, ] const router = new VueRouter({   mode: 'history',   base: process.env.BASE_URL,   routes }) export default router
Code Splitting (코드 분할)
- SPA의 성능을 향상시키는 방법 (비동기적으로 컴포넌트를 로딩)
- SPA는 초기 실행시 필요한 웹 자원을 모두 다운 받는 특징이 있음
- Code Splitting을 활용하면 필요한 시점에 다운 받아 초기 로딩 시간 단축 가능

component: () => import('@/components/book/BookList.vue') 방식 = Code Splitting 지원

 

'WEB > front-end' 카테고리의 다른 글

React 기초 정리  (0) 2025.03.14
[Vue 기초 7] axios 비동기  (0) 2023.05.14
[Vue 기초 5] vue-cli/npm  (1) 2023.05.14
[Vue 기초 4] Component  (0) 2023.05.14
[Vue 기초 3] Event, Binding  (0) 2023.05.05
profile

danbibibi

@danbibibi

꿈을 꾸는 시간은 멈춰 있는 것이 아냐 두려워하지 마 멈추지 마 푸른 꿈속으로