使用 vue-router 登录后重定向到请求的页面 [英] Redirect to requested page after login using vue-router

查看:68
本文介绍了使用 vue-router 登录后重定向到请求的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,某些路由只能供经过身份验证的用户访问.
当未经身份验证的用户单击链接时,他必须登录,他将被重定向到登录组件.

如果用户登录成功,我想将他重定向到他必须登录前请求的 URL.但是,还应该有一个默认路由,以防用户在登录之前没有请求另一个 URL.

如何使用 vue-router 实现这一点?


登录后没有重定向的代码

In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redirected to the login component.

If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.

How can I achieve this using vue-router?


My code without redirect after login

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('/')
          })



我会非常感谢任何形式的帮助!



I would be very thankful for any kind of help!

推荐答案

这可以通过在路由中添加重定向路径作为查询参数.

This can be achieved by adding the redirect path in the route as a query parameter.

然后登录的时候要检查redirect参数是否设置:
- 如果 IS 将重定向设置为在 param
中找到的路径- 如果未设置,您可以回退到 root.

Then when you login, you have to check if the redirect parameter is set:
- if IS set redirect to the path found in param
- if is NOT set you can fallback on root.

为您的链接添加操作,例如:

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*/ })
}

希望有帮助.

这篇关于使用 vue-router 登录后重定向到请求的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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