的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,
// ...
})
謝謝@Ikbel ..這解決了這個問題 –