如何在 vue-router beforeRouteEnter 挂钩中重定向到不同的 url?
How to redirect to a different url inside the vue-router beforeRouteEnter hook?
我正在使用 Vue.js 2 构建一个管理页面,我想防止未经身份验证的用户访问 /admin
路由并将他们重定向到 /login
。为此,我在 Admin 组件中使用了 In-Component Guard beforeRouteEnter
,如下所示
...
beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
this.$router.push('/login');
}
}
这里的问题是 this
没有在 beforeRouteEnter
钩子中定义。那么在这种情况下访问 $router
并重定向到另一个 url 的正确方法是什么?
documentation 指出:
The beforeRouteEnter
guard does NOT have access to this
, because the
guard is called before the navigation is confirmed, thus the new
entering component has not even been created yet.
您可以像这样调用 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,
// ...
})
我正在使用 Vue.js 2 构建一个管理页面,我想防止未经身份验证的用户访问 /admin
路由并将他们重定向到 /login
。为此,我在 Admin 组件中使用了 In-Component Guard beforeRouteEnter
,如下所示
...
beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
this.$router.push('/login');
}
}
这里的问题是 this
没有在 beforeRouteEnter
钩子中定义。那么在这种情况下访问 $router
并重定向到另一个 url 的正确方法是什么?
documentation 指出:
The
beforeRouteEnter
guard does NOT have access tothis
, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.
您可以像这样调用 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,
// ...
})