네비게이션 가드

해듬이 아빠·2021년 3월 5일
0

vue-router가 제공하는 네비게이션 가드는 주로 리디렉션하거나 취소하여 네비게이션을 보호하는 데 사용됩니다.

전역 가드

전역 가드는 라우터 인스턴스를 참조하는 객체로 설정할 수 있습니다.

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // to : 이동할 url
  // from : 현재 url
  // next : to에서 지정한 url로 이동하기 위해 꼭 호출해야 하는 함수
})

router.beforeEach()를 호출하고 나면 모든 라우팅이 대기 상태가 됩니다.
원래 url이 변경되고 나면 해당 url에 따라 화면이 자연스럽게 전환되어야 하는데 전역 가드를 설정했기 때문에 화면이 전환되지 않습니다.
여기서 해당 url로 라우팅 하기 위해서는 next()를 호출해줘야 합니다.

전역가드동작예제

var Login = { template: '<p>Login Component</p>'};
var Home = { template: '<p>Home Component</p>'};

var router = new VueRouter({
	routes: [
		{path: '/login', component: Login},
		{path: '/home', component: Home}
	]
});

router.beforeEach(function (to, from, next) {
  console.log('every single routing is pending');
  //만약 원하는 url로 이동하고 싶으면 아래와 같이 next()를 호출하면 됩니다.
  next();
});

new Vue({
	el: '#app',
	router
});

전역가드 페이지 인증 예제

Login 컴포넌트에 다음과 같이 meta 정보를 추가
var router = new VueRouter({
  routes: [
    // meta 정보에 authRequired라는 Boolean 값 추가
    { path: '/login', component: Login, meta: {authRequired: true} },
    { path: '/home', component: Home }
  ]
});
beforeEach()의 콜백 함수에 사용자 인증 여부를 체크하는 로직을 추가
router.beforeEach(function (to, from, next) {
  // to: 이동할 url에 해당하는 라우팅 객체
  if (to.matched.some(function(routeInfo) {
    return routeInfo.meta.authRequired;
  })) {
    // 이동할 페이지에 인증 정보가 필요하면 경고 창을 띄우고 페이지 전환은 하지 않음
    alert('Login Please!');
  } else {
    console.log("routing success : '" + to.path + "'");
    next(); // 페이지 전환
  };
});

라우터 가드

var router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login,
      beforeEnter: function(to, from, next) {
        // 인증 값 검증 로직 추가
      }
    }
  ]
})

컴포넌트 가드

const Login = {
  template: '<p>Login Component</p>',
  beforeRouteEnter (to, from, next) {
    // Login 컴포넌트가 화면에 표시되기 전에 수행될 로직
    // Login 컴포넌트는 아직 생성되지 않은 시점
  },
  beforeRouteUpdate (to, from, next) {
    // 화면에 표시된 컴포넌트가 변경될 때 수행될 로직
    // `this`로 Login 컴포넌트를 접근할 수 있음
  },
  beforeRouteLeave (to, from, next) {
    // Login 컴포넌트를 화면에 표시한 url 값이 변경되기 직전의 로직
    // `this`로 Login 컴포넌트를 접근할 수 있음
  }
}

라우터 가드 예제

//route.js
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const requireAuth = (to, from, next) => {
  const isAuth = localStorage.getItem('token')
  const loginPath = `/login?Path=${encodeURIComponent(to.path)}`
  isAuth ? next() : next(loginPath)
}

const router = new VueRouter({
  mode : 'history',
  routes: [
    {path: '/', component: Home, beforeEnter: requireAuth },
    {path: '/login', component: Login},
    {path: '/b/:bid', component: Board, beforeEnter: requireAuth, children : [
        { path : 'c/:cid', component: Card, beforeEnter: requireAuth}
    ]},
    {path: '*', component: NotFound}
  ]
})
profile
즐거운 코딩생활

0개의 댓글