programing

RouteEnter 후크 전에 vue-router 내의 다른 URL로 리디렉션하는 방법?

prostudy 2022. 3. 14. 21:44
반응형

RouteEnter 후크 전에 vue-router 내의 다른 URL로 리디렉션하는 방법?

Vue.js 2와 함께 관리 페이지를 작성하고 있으며 인증되지 않은 사용자가 액세스하지 못하도록 차단하고 싶다./admin경로를 지정하고 로 리디렉션/login. 그러기 위해 나는 구성 요소 내 가드를 사용해 왔다.beforeRouteEnter다음과 같은 Admin 구성 요소에서

...
beforeRouteEnter(to, from, next) {
  if(userNotLogedIn) {
    this.$router.push('/login');
  }
}

여기서 문제는 이다.this정의되지 않음beforeRouteEnter훅이야 그럼 어떻게 접근하는 게 좋을까?$router그리고 이 경우 다른 URL로 리디렉션하시겠습니까?

문서에는 다음과 같이 명시되어 있다.

beforeRouteEnter가드가 에 접근할 수 없음this항법이 확정되기 전에 가드를 호출하기 때문에, 아직 새로운 진입 구성요소가 만들어지지도 않았다.

호출하여 다른 페이지로 리디렉션할 수 있음next다음과 같은 경우:

beforeRouteEnter(to, from, next) {
  if(userNotLogedIn) {
    next('/login');
  }
}

동일한 결과를 얻기 위한 또 다른 방법이 있다.그래서 사용하는 대신에beforeRouteEnter각 보호된 경로에서, 당신은 라우터 구성에서 보호되는 경로를 정의할 수 있다.meta속성, 그런 다음beforeEach모든 경로를 잠그고 보호된 경로를 확인하고 필요한 경우 로그인 페이지로 리디렉션:

let router = new Router({    
  mode: 'history',    
  routes: [    
    {
      path: '/profile',
      name: 'Profile',
      component: Profile,
      meta: {
        auth: true // A protected route
      },
    },    
    {
      path: '/login',
      name: 'Login',
      component: Login, // Unprotected route
    },
  ]
})

/* Use this hook on all the routes that need to be protected 
instead of beforeRouteEnter on each one explicitly */

router.beforeEach((to, from, next) => {    
  if (to.meta.auth && userNotLoggedIn) {
    next('/login')
  }    
  else {
    next()
  }    
})

// Your Vue instance
new Vue({
  el: '#app',
  router,
  // ...
})

참조URL: https://stackoverflow.com/questions/45701595/how-to-redirect-to-a-different-url-inside-the-vue-router-beforerouteenter-hook

반응형