클라이언트 측 라우팅 (Client-Side Routing)
클라이언트 측 라우팅은 브라우저가 페이지를 다시 로드하지 않고도 URL을 변경하고, URL 변경 시 페이지의 뷰를 변경하는 것을 가능하게 하는 기술입니다. 이는 단일 페이지 애플리케이션(Single-Page Application, SPA)에서 사용자 경험을 향상시키는 데 사용됩니다.
전통적인 웹 애플리케이션(서버 측 라우팅)에서는, URL 변경 시마다 서버에 새로운 HTML 페이지를 요청합니다. SPA에서는, 애플리케이션이 초기에 한 번만 로드되고, 그 이후의 모든 뷰 변경은 클라이언트 측에서 JavaScript에 의해 처리됩니다.
공식 라우터 (Official Router)
대부분의 SPA에서는 공식적으로 지원되는 Vue Router 라이브러리를 사용하는 것이 좋습니다. Vue Router는 Vue.js와 깊이 통합되어 있으며, 중첩된 라우트, 뷰 트랜지션, 지연 로딩 등과 같은 고급 기능을 제공합니다.
Vue Router 시작하기
Vue Router를 시작하려면, 먼저 프로젝트에 설치해야 합니다:
npm install vue-router@4
그런 다음, 라우터 인스턴스를 생성하고 라우트 정의를 전달합니다:
// main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
// 1. 라우트 컴포넌트를 정의합니다.
// 다른 파일에서 가져올 수 있습니다.
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. 일부 라우트를 정의합니다.
// 각 라우트는 컴포넌트에 매핑되어야 합니다.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. 라우터 인스턴스를 생성하고 `routes` 옵션을 전달합니다.
// 여기서는 간단하게 하기 위해 해시 모드를 사용하고 있습니다.
const router = createRouter({
// 4. 내부적으로 사용할 히스토리 구현을 제공합니다.
// 여기서는 간단하게 하기 위해 해시 모드를 사용하고 있습니다.
history: createWebHistory(),
routes, // `routes: routes`의 약식
})
// 5. 루트 컴포넌트를 생성하고 마운트합니다.
const app = createApp(App)
// 전체 앱이 라우터를 인식하도록 합니다.
app.use(router)
app.mount('#app')
앱의 템플릿에서 <router-view>
를 사용하여 현재 라우트에 해당하는 컴포넌트를 렌더링하고, <router-link>
를 사용하여 탐색 링크를 생성할 수 있습니다.
<!-- App.vue -->
<template>
<h1>Hello App!</h1>
<p>
<!-- use router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will be rendered as an `<a>` tag by default -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</template>
간단한 라우팅 직접 만들기 (Simple Routing from Scratch)
매우 간단한 라우팅만 필요하고 완전한 기능의 라우터 라이브러리를 포함하고 싶지 않다면, 동적 컴포넌트를 사용하고 현재 URL 해시 변경을 수신하거나 History API를 사용하여 현재 컴포넌트 상태를 업데이트할 수 있습니다.
다음은 간단한 예입니다:
<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'
const routes = {
'/': Home,
'/about': About
}
const currentPath = ref(window.location.hash)
window.addEventListener('hashchange', () => {
currentPath.value = window.location.hash
})
const currentView = computed(() => {
return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>
<template>
<a href="#/">Home</a> |
<a href="#/about">About</a> |
<a href="#/non-existent-path">Broken Link</a>
<component :is="currentView" />
</template>
반응형