네비게이션 가드를 뷰에서 이용하기 위해서는 beforeEach 메서드를 사용한다.

해당 메서드는 VueRouter 객체에서 routes path를 먼저 만든 후, 모든 라우터 변경이 일어날 때 적용할 로직을 작성하여 사용할 수 있다. routes/index.js 파일에서 다음과 같이 사용한다.

// routes/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    ...
  ],
});

router.beforeEach((to, from, next) => {
  ... // some logic
  next();
});

export default router;

beforeEach는 세 가지 인자를 받는다.

페이지별 인증 권한 설정

인증이 필요한 페이지와 인증 없이 접근할 수 있는 페이지를 나눠본다. 이 때 사용하는 방식이 router path 안의 meta 속성이다.

const router = new VueRouter({
  mode: 'history',
  routes: [
		...
		{
      path: '/main',
      component: () => import('@/views/MainPage.vue'),
      **meta: { auth: true }**
    },
    {
      path: '/add',
      component: () => import('@/views/PostAddPage.vue'),
      **meta: { auth: true }**
    },
    {
      path: '/post/:id',
      component: () => import('@/views/PostEditPage.vue'),
      **meta: { auth: true }**
    },
	...
	],
...

meta 태그 안에 auth라는 속성이 true여야지만 해당 path에 접근이 가능한 형태로 만들었다. auth 속성은 임의로 프로그래머가 만들어야 하는 속성이다.

beforeEach에서 to 인자의 meta 태그 안의 auth 속성에 접근해 네비게이션 가드를 설정한다.

router.beforeEach((to, from, next) => {
  if (to.meta.auth) { 
    // 가려고 하는 페이지의 meta 안의 auth 속성이 true라면...
    console.log('you need authentication');
  }
  next();
});

대부분의 경우 store에서 로그인 여부에 대한 state를 관리한다. 이 state를 getter로 가져와 meta 속성과 함께 조건문에 넣는다.

router.beforeEach((to, from, next) => {
  if (to.meta.auth && !store.getters.isLogin) {
    console.log('you need authentication');
    next('/login');
		return; // 불필요한 아랫쪽의 next가 실행되지 않도록
  }
  next();
});