2017-09-18 1 views
0

로그인하지 않은 사용자가 액세스 할 수없는 구성 요소가 있습니다. 이 로직을 beforeCreate 후크에 구현했습니다. 문제는 이것으로 컴포넌트가 계속해서 로딩되는 것을 멈추지 않는다는 것입니다.Vue에서 구성 요소로드 및 리디렉션을 중지하는 방법은 무엇입니까?

<script> 
    export default { 
     beforeCreate: function() { 
      if (this.$root.auth.user === null) { 
       this.$router.push({ name: 'auth.login' }) 
      } 
     }, 

     mounted: function() { 
      // some code that SHOULD NOT be processed 
      // if the user isn't authenticated 
     } 
    } 
</script> 

내가 잘못 뭐하는 거지 :

이 내 코드?

답변

1

beforeCreate 함수를 라우터 자체로 옮겨야합니다. 다음은이 날 인증 및 게스트 게재 위치를 처리하기 위해 내 경로 정의를 사용할 수 있습니다 내 인증 캐치

router.beforeEach(
    (to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
     // if route requires auth and user isn't authenticated 
     if (!store.state.Authentication.authenticated) { 
     let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath } 
     next(
      { 
      path: '/login', 
      query: query 
      } 
     ) 
     return 
     } 
    } 
    next() 
    } 
) 

입니다.

{ 
    path: '/', 
    component: load('Template'), 
    children: [ 
    { path: '', component: load('Dashboard'), name: 'Dashboard' } 
    ], 
    meta: { requiresAuth: true } 
}, 
{ 
    path: '/login', 
    component: load('Authentication/Login'), 
    name: 'login' 
}, 

구성 요소가 Vue에 의해 초기화되기 전에 라우터에서 호출되면 구성 요소 수준 이벤트 처리가 중지됩니다.

관련 문제