[Vue] Router

전상욱·2022년 1월 22일
0

Vue

목록 보기
3/3
post-thumbnail

클라이언트의 요청 경로에 따라 해당하는 컴포넌트를 불러와 페이지를 구성할 수 있다.
URL 변경 시 DOM을 새로 갱신하는 것이 아니라 미리 컴포넌트를 가지고 있다가 변경된 요소영역만 갱신한다. (SPA 언어의 큰 특징)
따라서 유연하게 페이지 전환이 가능하다. vue 프레임워크에서는 vue-router라는 라우팅 라이브러리를 지원한다.

Router Install

// CDN
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

// NPM
$npm install vue-router --save

Router Option

라우터 인스턴스를 생성할 때 옵션

  • String mode: 기본 값은 hash모드 (history모드를 사용하면 브라우저 히스토리 스택에 기록된다.)
  • String redirect: 리다이렉팅 (주로 메인 페이지 등에 사용한다.)
  • Array routes: 페이지 라우팅 정보
    • String path: 페이지 경로 (url)
    • Object component: 해당 url페이지에 사용할 컴포넌트
    • Array children: 중첩 라우팅을 위한 배열
// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', redirect: () => import('/home') },
    { path: '/home', component: () => import('./Main.vue') },
    { path: '/info', component: () => import('./Info.vue') }
  ]
});

export default router;
import Vue from 'vue';
import router from './router.js';

new Vue({
  router,
  render: h => h (App)
}).$mount('#root');

라우터 URL 이동
<router-link to="/home">home 이동</router-link>

라우터 컴포넌트 표시
<router-view />

profile
더 높은 곳으로

0개의 댓글