javascript – 如何重定向到vue-router beforeRouteEnter钩子内的不同url?

前端之家收集整理的这篇文章主要介绍了javascript – 如何重定向到vue-router beforeRouteEnter钩子内的不同url?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Vue.js 2构建管理页面,我想阻止未经身份验证的用户访问/ admin路由并将其重定向到/ login.为此我在Admin组件中使用了之前的组件保护,如下所示
  1. ...
  2. beforeRouteEnter(to,from,next) {
  3. if(userNotLogedIn) {
  4. this.$router.push('/login');
  5. }
  6. }

这里的问题是在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来重定向到另一个页面

  1. beforeRouteEnter(to,next) {
  2. if(userNotLogedIn) {
  3. next('/login');
  4. }
  5. }

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

  1. let router = new Router({
  2. mode: 'history',routes: [
  3. {
  4. path: '/profile',name: 'Profile',component: Profile,Meta: {
  5. auth: true // A protected route
  6. },},{
  7. path: '/login',name: 'Login',component: Login,// Unprotected route
  8. },]
  9. })
  10.  
  11. /* Use this hook on all the routes that need to be protected
  12. instead of beforeRouteEnter on each one explicitly */
  13.  
  14. router.beforeEach((to,next) => {
  15. if (to.Meta.auth && userNotLoggedIn) {
  16. next('/login')
  17. }
  18. else {
  19. next()
  20. }
  21. })
  22.  
  23. // Your Vue instance
  24. new Vue({
  25. el: '#app',router,// ...
  26. })

猜你在找的JavaScript相关文章