首页 文章

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

提问于
浏览
12

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

如果用户成功登录, I would like to redirect him to the URL he requested before he had to log in . 但是, there also should be a default route ,以防用户在登录前未请求其他URL .

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

My login function in my login component

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

我会非常感谢任何帮助!

4 回答

  • 11

    以一种不同的方式,这可以通过在您想要重定向时在路由中添加查询参数来实现,然后在设置参数时检查您何时登录;如果已设置,则使用它或以其他方式回退root .

    在代码中应该看起来像这样:

    Put an action to your link for example:

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

    The login submit action

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

    希望能帮助到你 .

  • 0

    我知道这是旧的,但它是谷歌的第一个结果,对于那些只想要它给你的人,这是你添加到你的两个文件 . 在我的情况下,我使用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); 它会将它们发送到我们之前生成的查询网址 .

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

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

  • 0

    Much easier with this library和登录功能是

    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
      })
    
  • 4

    这将有助于你@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()
        }
    );
    

相关问题