2017-08-24 136 views
6

在我的应用程序的一些途径只是通过验证的用户访问重定向到请求的页面登录后。
当一个未经验证的用户点击一个链接,为此他必须签署,他将被重定向到登录组件。

如果用户成功登录,我想他重定向到之前,他必须进行登录他请求的URL。然而,也应该有一个默认路由,万一他在登录之前用户没有请求另一个URL。

我怎样才能做到这一点使用VUE路由器?
使用VUE路由器


我不重定向代码登录后

router.beforeEach(
    (to, from, next) => { 
     if(to.matched.some(record => record.meta.forVisitors)) { 
      next() 
     } else if(to.matched.some(record => record.meta.forAuth)) { 
      if(!Vue.auth.isAuthenticated()) { 
       next({ 
        path: '/login' 
        // Redirect to original path if specified 
       }) 
      } else { 
       next() 
      } 
     } else { 
      next() 
     } 
    }   
) 



在我登录组件我的登录功能

login() { 
    var data = { 
     client_id: 2, 
     client_secret: '**************', 
     grant_type: 'password', 
     username: this.email, 
     password: this.password 
    } 
    // send data 
    this.$http.post('oauth/token', data) 
     .then(response => { 
      // authenticate the user 
      this.$auth.setToken(response.body.access_token, 
      response.body.expires_in + Date.now()) 
      // redirect to route after successful login 
      this.$router.push('/') 
      }) 



我将是任何形式的非常感谢帮帮我!

+13

你可以做类似'下一个({路径:“?/登录从=” + to.path})',然后你的登录页面上检查'from'查询参数设置,并做了重定向 –

+0

@ FlorianHaider这听起来像是一个很好的解决方案!如何检查从我的登录组件设置的查询参数? – Schwesi

+3

@Schwesi你使用'this。$ route.query.from'获得查询参数。如果没有查询出现,你会得到一个空物体 –

回答

2

在有点不同的方式,这可以通过在你的路径添加查询参数时要重定向,然后当你登录,如果参数是设置检查来实现;如果已设置,则使用它或以其他方式在根目录上回退。

在代码应该是这个样子:

把一个行动,你的链接,例如:

onLinkClicked() { 
    if(!isAuthenticated) { 
    // If not authenticated, add a path where to redirect after login. 
    this.$router.push({ name: 'login', query: { redirect: '/path' } }); 
    } 
} 

登录提交操作

submitForm() { 
    AuthService.login(this.credentials) 
    .then(() => this.$router.push(this.$route.query.redirect || '/')) 
    .catch(error => { /*handle errors*/ }) 
} 

希望它帮助。