Vue3에서는 Vue Router도 함께 업그레이드되어, Vue Router 4가 출시되었습니다. Composition API에 최적화되었고, TypeScript 지원이 강화되었으며, 동적 라우팅 및 코드 분할 등의 기능이 더 효율적으로 동작합니다. 이 글에서는 Vue Router 4의 기본 개념부터 실무에서 자주 쓰는 예제까지 모두 정리해보겠습니다.
Vue Router 4란?
Vue Router 4는 Vue3에서 공식 지원하는 라우팅 라이브러리입니다. 페이지 전환, 동적 라우팅, 네비게이션 가드, 네임드 뷰 등 SPA 개발에서 필수적인 기능을 제공합니다.
1. 설치 및 기본 설정
npm install vue-router@4
router/index.js 또는 router/index.ts 파일을 만들어 다음과 같이 설정합니다.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue') // 코드 스플리팅
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
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')
2. <router-link>와 <router-view> 기본 사용법
<!-- App.vue -->
<template>
<nav>
<router-link to="/">홈</router-link>
<router-link to="/about">소개</router-link>
</nav>
<router-view />
</template>
3. 동적 라우트(Dynamic Route)
{
path: '/user/:id',
name: 'user',
component: UserView
}
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const userId = route.params.id
</script>
4. 네비게이션 가드
// router/index.js
router.beforeEach((to, from, next) => {
const isAuthenticated = true // 로그인 여부 예시
if (to.name !== 'home' && !isAuthenticated) {
next({ name: 'home' })
} else {
next()
}
})
Composition API에서도 다음과 같이 사용할 수 있어요:
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave((to, from) => {
const leave = window.confirm('정말 페이지를 나가시겠습니까?')
if (!leave) return false
})
5. Named Views (이름 있는 뷰)
{
path: '/layout',
components: {
default: MainView,
sidebar: SidebarView
}
}
<router-view />
<router-view name="sidebar" />
6. 중첩 라우트(Nested Route)
{
path: '/dashboard',
component: DashboardLayout,
children: [
{
path: 'stats',
component: StatsView
},
{
path: 'settings',
component: SettingsView
}
]
}
<router-view> 안에 또 다른 <router-view>를 배치하면 자식 컴포넌트가 출력됩니다.
7. 라우터 푸시와 네비게이션
import { useRouter } from 'vue-router'
const router = useRouter()
const goToUser = () => {
router.push({ name: 'user', params: { id: 123 } })
}
실무 팁
- 코드 스플리팅: component: () => import(...) 형태로 lazy loading을 적용하면 앱 속도가 향상됩니다.
- Named View와 중첩 라우트는 대시보드, 관리자 화면 등에서 구조적으로 매우 유용합니다.
- useRoute, useRouter 훅은 Composition API에서 라우팅 정보를 제어할 때 핵심입니다.
- 404 처리는 마지막에 path: '/:pathMatch(.*)*' 형태로 지정하면 됩니다.
Vue Router 4는 Vue3의 Composition API와 찰떡궁합이며, SPA를 만들기 위한 필수 기능을 제공합니다. 기존 Vue2 방식과 비슷하면서도 더 명확한 구조와 개선된 타입 지원으로, 더욱 강력하고 안전한 라우팅을 구현할 수 있습니다.
'프로그래밍' 카테고리의 다른 글
Vue3와 TypeScript 통합 사용법 (1) | 2025.07.30 |
---|---|
Vue3 상태 관리는 이제 Pinia로! Vuex 대체 라이브러리 Pinia 완벽 가이드 (0) | 2025.07.29 |
Vue3 컴포지션 API로 재사용 로직을 구조화하는 방법 – useXXX() 패턴으로 깔끔한 코드 만들기 (1) | 2025.07.29 |
Vue3에서 Slots는 어떻게 달라졌을까? – 기본 슬롯부터 named slot, scoped slot까지 정리 (2) | 2025.07.29 |
Vue3에서의 Dynamic Components: 더 깔끔하고 직관적으로! (0) | 2025.07.28 |