的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 ..这解决了这个问题 –