Web Development/vue

[콜럼Vue스] Vue-router

쟤리 2024. 10. 20. 17:25
728x90
반응형

vue-router는 Vue.js 에서 공식적으로 제공하는 클라이언트 측 라우팅 라이브러리임.

이를 사용하면 Vue.js 애플리케이션 내에서 여러 페이지 또는 컴포넌트 간에 라우팅을 쉽게 처리할 수 있음

 

기본사용법

라우터설정 -> 라우터 사용 -> 라우트 링크와 라우트 표시

라우터설정

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

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

export default router

라우터사용

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router) // 라우터 등록
app.mount('#app')

라우트 링크와 라우트 표시

<template>
  <div>
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
    </nav>

    <!-- 현재 라우트에 맞는 컴포넌트를 표시 -->
    <router-view></router-view>
  </div>
</template>

 

router 객체와 currentRoute 객체

컴포넌트에서의 Router 관련 정보 접근

  Option API Composition API
라우터 객체 this.$router const router = useRouter()
매칭된 라우트 (CurrentRoute) this.$route 또는
this.$router.currentRoute
const currentRoute = useRoute()

 

currentRoute 객체의 주요 속성

구분 설명
fullpath 전체 요청 경로, 쿼리문자열까지 포함 (about?a=1&b=2)
matched vue-router 객체의 routes 배열의 라우트 중 매칭된 라우트
parmas URI 경로에 동적으로 전달된 파라미터 정보
path 요청 URI 경로
query 쿼리 문자열 정보 ?a=1&b=2로 요청되었다면 this.$route.query는 {a:1,b:2}와 같은 객체임
redirectedForm 다른 경로에서 리디렉트된 경우 리디렉트시킨 URI 경로 정보를 포함

 


주요 개념

  1. 라우트(route): 특정 URL에 해당하는 페이지 또는 컴포넌트를 의미함.
  2. 라우터(router): 애플리케이션의 라우트를 관리하는 객체.
  3. 네비게이션 가드: 사용자가 특정 라우트로 이동하려 할 때, 이동을 제어할 수 있는 기능.

참고자료 : 원쌤의 퀵 Vue.js

728x90
반응형

'Web Development > vue' 카테고리의 다른 글

[콜럼Vue스] 중첩라우트  (0) 2024.10.21
[콜럼Vue스] 동적라우트  (0) 2024.10.21
[콜럼Vue스] <script setup>  (0) 2024.10.19
[콜럼Vue스] 생명주기 훅(Life Cycle Hook)  (0) 2024.10.19
[콜럼Vue스] Watch, WatchEffect  (0) 2024.10.18