作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在使用 Vue.js 2 构建一个管理页面,我想阻止未经身份验证的用户访问 /admin
路由并将他们重定向到 /login
。为此,我在 Admin 组件中使用了 In-Component Guard beforeRouteEnter
,如下所示
...
beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
this.$router.push('/login');
}
}
这里的问题是 this
没有在 beforeRouteEnter
钩子(Hook)中定义。那么在这种情况下访问 $router
并重定向到不同 url 的正确方法是什么?
最佳答案
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
属性在路由器配置中定义 protected 路由,而不是在每个 protected 路由上使用 beforeRouteEnter
,然后在所有路由上使用 beforeEach
Hook 并检查 protected 路由并在需要时重定向到登录页面:
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,
// ...
})
关于javascript - 如何在 vue-router beforeRouteEnter 钩子(Hook)中重定向到不同的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701595/
我是一名优秀的程序员,十分优秀!