简体   繁体   English

如何在路由器挂钩之前重定向到vue-router内的不同URL?

[英]How to redirect to a different url inside the vue-router beforeRouteEnter hook?

I am building an admin page with Vue.js 2 and I want to prevent unauthenticated users from accessing the /admin route and redirect them to /login . 我正在使用Vue.js 2构建管理页面,我想阻止未经身份验证的用户访问/admin路由并将其重定向到/login For that I have used the In-Component Guard beforeRouteEnter in the Admin component like follows 对于我已经使用了In-组件卫队beforeRouteEnter在管理组件类似如下

...
beforeRouteEnter(to, from, next) {
  if(userNotLogedIn) {
    this.$router.push('/login');
  }
}

The problem here is that this is not defined in beforeRouteEnter hook. 这里的问题是, this是不是在定义beforeRouteEnter挂钩。 So what's the proper way to access $router and redirect to a different url in this case ? 那么在这种情况下访问$router并重定向到不同url的正确方法是什么?

The documentation states that: 文件指出:

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. beforeRouteEnter后卫无权访问this ,因为在确认导航之前调用了后卫,因此尚未创建新的输入组件。

You can redirect to another page by calling next like this: 你可以通过调用next来重定向到另一个页面:

beforeRouteEnter(to, from, next) {
  if(userNotLogedIn) {
    next('/login');
  }
}

Here is another way to accomplish the same result: So instead of using beforeRouteEnter on each protected route, you could define protected routes in your router configuration using a meta property, then use beforeEach hook on all the routes and check for protected routes and redirect to login page when needed: 以下是实现相同结果的另一种方法:因此,不是在每个受保护的路由上使用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,
  // ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM