네비게이션 가드는 주로 페이지 이동을 리다이렉션 하거나 취소하여 특정 페이지 진입을 보호하는 데 사용됩니다. 페이지(라우트)를 이동하기 전에 특정 로직을 실행할 수 있도록 하는 기능으로 인증, 권한 검증 또는 데이터를 미리 불러오는 작업을 처리하기 위해 사용됩니다. Vue Router를 사용하여 설정하며, 네비게이션 과정에서 가드를 통해 라우트 전환을 제어할 수 있습니다.
전역 네비게이션 가드는 모든 라우트 이동에서 트리거됩니다. Vue Router 인스턴스를 설정할 때 추가할 수 있습니다.
예시 코드
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// 전역 beforeEach 가드
router.beforeEach((to, from, next) => {
console.log('Global Before Guard');
// 인증 예시
if (to.meta.requiresAuth && !isUserAuthenticated()) {
next('/login'); // 인증되지 않은 경우 로그인 페이지로 리디렉션
} else {
next(); // 인증된 경우 네비게이션 진행
}
});
// 전역 afterEach 가드 (네비게이션 완료 후 호출)
router.afterEach((to, from) => {
console.log('Global After Guard');
});
export default router;
개별 라우트에만 특정 네비게이션 가드를 적용할 수 있습니다. 이를 통해 특정 라우트에 대해 동작하는 로직을 커스터마이즈할 수 있습니다.
const routes = [
{
path: '/dashboard',
component: () => import('./components/Dashboard.vue'),
meta: { requiresAuth: true }, // 인증이 필요한 경로
beforeEnter: (to, from, next) => {
console.log('Route-specific Before Enter');
// 인증 예시
if (!isUserAuthenticated()) {
next('/login'); // 인증되지 않은 경우 로그인 페이지로 리디렉션
} else {
next(); // 인증된 경우 네비게이션 진행
}
},
},
];
컴포넌트에 정의된 네비게이션 가드는 컴포넌트 내에서 발생하는 라우트 전환에 대해 실행됩니다. 컴포넌트의 생명주기와 밀접하게 연관되어 있으며, 컴포넌트의 상태를 기반으로 네비게이션을 제어할 수 있습니다.
export default {
template: `<div>Profile</div>`,
// 컴포넌트가 활성화되기 전에 호출
beforeRouteEnter(to, from, next) {
console.log('Component-specific Before Enter');
next(); // 라우트 전환 허용
},
// 현재 컴포넌트에서 라우트가 변경될 때 호출
beforeRouteUpdate(to, from, next) {
console.log('Component-specific Before Update');
next(); // 라우트 전환 허용
},
// 컴포넌트가 떠나기 전에 호출
beforeRouteLeave(to, from, next) {
console.log('Component-specific Before Leave');
const answer = window.confirm('이 페이지를 떠나시겠습니까?');
if (answer) {
next(); // 라우트 전환 허용
} else {
next(false); // 라우트 전환 중단
}
},
};