如何在路由器挂钩之前重定向到vue-router内的不同URL? [英] How to redirect to a different url inside the vue-router beforeRouteEnter hook?

查看:468
本文介绍了如何在路由器挂钩之前重定向到vue-router内的不同URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue.js 2构建管理页面,我想阻止未经身份验证的用户访问 / admin 路由并将其重定向到 /登录。为此我在Admin组件中使用了In-Component Guard beforeRouteEnter ,如下所示

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. For that I have used the In-Component Guard beforeRouteEnter in the Admin component like follows

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

这里的问题是未在 beforeRouteEnter hook中定义。那么在这种情况下访问 $ router 并重定向到不同网址的正确方法是什么?

The problem here is that this is not defined in beforeRouteEnter hook. So what's the proper way to access $router and redirect to a different url in this case ?

推荐答案

文档指出:


beforeRouteEnter 后卫无法访问,因为在确认导航之前调用
后卫,因此尚未创建新的
输入组件。

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 重定向到另一个页面:

You can redirect to another page by calling next like this:

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

这是实现相同结果的另一种方法:所以而不是在每个受保护的路由上使用 beforeRouteEnter ,您可以使用 meta 属性在路由器配置中定义受保护的路由,然后在所有路线上使用 beforeEach 挂钩并检查受保护的路线并在需要时重定向到登录页面:

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:

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-router内的不同URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆