2017-08-15 141 views
3

我正在用Vue.js 2構建一個管理頁面,我想阻止未經身份驗證的用戶訪問/admin路由並將它們重定向到/login。對於我已經使用了In-組件衛隊beforeRouteEnter在管理組件類似如下如何重定向到vue-router beforeRouteEnter掛鉤內的其他url?

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

這裏的問題是,thisbeforeRouteEnter掛鉤定義。那麼在這種情況下,訪問$router並重定向到其他網址的正確方法是什麼?

回答

2

documentation指出:

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, 
    // ... 
}) 
+0

謝謝@Ikbel ..這解決了這個問題 –

相關問題