这documentation条规定:
beforeRouteEnter
守卫无法进入this
,因为
您可以通过如下方式调用next
重定向到另一个页面:
beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
next('/login');
}
}
下面是实现相同结果的另一种方法:因此,您可以使用meta
属性在路由配置中定义受保护的路由,而不是在每个受保护的路由上使用beforeRouteEnter
,然后在所有路由上使用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,
// ...
})