问题 使用vue-router登录后重定向到请求的页面


在我的应用程序中,一些路由只对经过身份验证的用户可访
当未经身份验证的用户点击必须登录的链接时,他将被重定向到登录组件。

如果用户成功登录, 在他必须登录之前,我想将他重定向到他要求的URL。然而, 还应该有一个默认路线,如果用户在登录前没有请求其他URL。

如何使用vue-router实现此目的?


登录后我的代码没有重定向

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



我会非常感谢任何帮助!


2249
2017-08-24 08:44


起源

你可以做点什么 next({ path: '/login?from=' + to.path }) 然后检查您的登录页面 from 查询参数已设置并执行重定向 - Florian Haider
@FlorianHaider这听起来像是一个很棒的解决方案!如何检查来自我的登录组件的查询参数是否设置? - Schwesi
@Schwesi你得到了查询参数 this.$route.query.from。如果没有查询,则会得到一个空对象 - Vamsi Krishna
@VamsiKrishna太棒了!谢谢! - Schwesi


答案:


以一种不同的方式,这可以通过在您想要重定向时在路由中添加查询参数来实现,然后在设置参数时检查您何时登录;如果已设置,则使用它或以其他方式回退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*/ })
}

希望能帮助到你。


9
2018-01-15 23:13





我知道这已经过时了,但这是google中的第一个结果,对于那些只想要它给你的人来说这就是你添加到两个文件中的内容。在我的情况下,我使用firebase进行身份验证。

路由器

这里的关键是 const loginpath = window.location.pathname; 我得到他们第一次访问的相对路径,然后是下一行 next({ name: 'Login', query: { from: loginpath } }); 我在重定向中作为查询传递。

router.beforeEach((to, from, next) => {
  const currentUser = firebase.auth().currentUser;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !currentUser) {
    const loginpath = window.location.pathname;
    next({ name: 'Login', query: { from: loginpath } });
  } else if (!requiresAuth && currentUser) next('menu');
  else next();
});

登录页面

这里没有魔法你只会注意到我对用户进行身份验证的行为 this.$router.replace(this.$route.query.from); 它将它们发送到我们之前生成的查询URL。

signIn() {
      firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
        (user) => {
          this.$router.replace(this.$route.query.from);
        },
        (err) => {
          this.loginerr = err.message;
        },
      );
    },

我将更详细地充实这个逻辑,但它按原样运行。我希望这可以帮助那些遇到此页面的人。


2
2018-06-26 02:41



为我工作,很好的答案......我正在尝试很多其他方法来解决这个问题,比如将网址存储在localstorage中等等。但这是一个整洁而正确的方法来授权重定向 - kotAPI


这个库更容易 和登录功能是

let redirect = this.$auth.redirect();
this.$auth
  .login({
    data: this.model,
    rememberMe: true,
    redirect: { name: redirect ? redirect.from.name : "homepage",  query: redirect.from.query },
    fetchUser: true
  })

0
2018-03-29 09:34





这将有助于你@Schwesi。

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

0
2017-07-17 00:23