반응형
 

Vue.js 네비게이션 가드란 무엇인가?

Vue.js의 네비게이션 가드는 Vue Router에서 제공하는 기능으로, 특정 조건에 따라 라우트 전환을 허용하거나 거부할 수 있게 합니다. 이를 통해 다음과 같은 작업을 처리할 수 있습니다:

  • 인증되지 않은 사용자가 특정 페이지에 접근하는 것을 막기
  • 라우트 변경 전에 데이터를 가져오거나 상태를 초기화
  • 페이지 전환 중 사용자의 동작 확인 (예: 저장되지 않은 변경 사항 경고)

네비게이션 가드의 종류

Vue Router에서 사용할 수 있는 네비게이션 가드는 세 가지로 나뉩니다:

  1. 전역 가드
    모든 라우트 전환에 적용됩니다.
  2. 라우트별 가드
    특정 라우트에서만 작동합니다.
  3. 컴포넌트 가드
    컴포넌트 내에서 작동합니다.

네비게이션 가드 사용 방법

1. 전역 가드

전역 가드는 router.beforeEachrouter.afterEach를 사용하여 설정할 수 있습니다.

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

const routes = [
  { path: '/', component: Home },
  { path: '/dashboard', component: Dashboard }
];

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

// 전역 가드 설정
router.beforeEach((to, from, next) => {
  console.log('전역 가드 실행:', to.path);
  if (to.path === '/dashboard') {
    const isAuthenticated = false; // 인증 상태 확인
    if (!isAuthenticated) {
      alert('로그인이 필요합니다.');
      return next('/'); // 홈으로 리다이렉트
    }
  }
  next(); // 전환 허용
});

export default router;
 

2. 라우트별 가드

라우트 정의에 beforeEnter 옵션을 추가하여 특정 라우트에만 가드를 설정할 수 있습니다.

const routes = [
  { path: '/', component: Home },
  { 
    path: '/dashboard', 
    component: Dashboard,
    beforeEnter: (to, from, next) => {
      console.log('라우트별 가드 실행:', to.path);
      const isAuthenticated = false; // 인증 상태 확인
      if (!isAuthenticated) {
        alert('로그인이 필요합니다.');
        return next('/'); // 홈으로 리다이렉트
      }
      next(); // 전환 허용
    }
  }
];
 

3. 컴포넌트 가드

컴포넌트에서 beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave 훅을 사용하여 가드를 설정할 수 있습니다.

<script>
export default {
  name: 'Dashboard',
  beforeRouteEnter(to, from, next) {
    console.log('컴포넌트 가드 (enter):', to.path);
    next(); // 전환 허용
  },
  beforeRouteUpdate(to, from, next) {
    console.log('컴포넌트 가드 (update):', to.path);
    next(); // 전환 허용
  },
  beforeRouteLeave(to, from, next) {
    console.log('컴포넌트 가드 (leave):', from.path);
    if (confirm('이 페이지를 떠나시겠습니까?')) {
      next(); // 전환 허용
    } else {
      next(false); // 전환 취소
    }
  }
};
</script>
 

네비게이션 가드 활용 예제: 인증 시스템

아래는 네비게이션 가드를 활용하여 간단한 인증 시스템을 구현한 예제입니다.

import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import Login from './views/Login.vue';
import Dashboard from './views/Dashboard.vue';

const routes = [
  { path: '/', component: Home },
  { path: '/login', component: Login },
  { 
    path: '/dashboard', 
    component: Dashboard,
    meta: { requiresAuth: true } // 인증 필요 플래그
  }
];

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

// 전역 가드: 인증 처리
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    const isAuthenticated = false; // 인증 상태 확인
    if (!isAuthenticated) {
      alert('로그인이 필요합니다.');
      return next('/login'); // 로그인 페이지로 리다이렉트
    }
  }
  next(); // 전환 허용
});

export default router;
 

결론

Vue.js의 네비게이션 가드는 앱의 라우팅 로직을 제어하고, 사용자 경험을 관리하는 데 중요한 역할을 합니다. 인증 처리, 데이터 로딩, 사용자 경고 등의 작업에 효과적으로 활용할 수 있습니다. 상황에 따라 전역, 라우트별, 컴포넌트 가드를 적절히 조합해 사용하면 더욱 강력한 앱을 만들 수 있습니다.

 
반응형

'개발 부트캠프 > 프론트엔드' 카테고리의 다른 글

[Vue] Pinia (State Manager)  (1) 2024.12.26
[Vue] Props & Emit  (0) 2024.12.24
[Vue] 조건문&반복문 (v-if, v-for)  (0) 2024.12.23
[Vue] 데이터 바인딩(Data Binding)  (0) 2024.12.23
[Vue] 뷰 라우터(Vue Router)  (2) 2024.12.23

+ Recent posts