documentation 声明:
beforeRouteEnter 守卫无权访问this,因为
在导航确认之前调用guard,因此新的
输入组件还没有被创建。
您可以像这样调用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,
// ...
})