Redirect to requested page after login using vue-router

前端 未结 8 1937
臣服心动
臣服心动 2020-12-07 20:40

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 redi

8条回答
  •  失恋的感觉
    2020-12-07 21:04

    I know this is old but it's the first result in google and for those of you that just want it given to you this is what you add to your two files. In my case I am using firebase for auth.

    Router

    The key line here is const loginpath = window.location.pathname; where I get the relative path of their first visit and then the next line next({ name: 'Login', query: { from: loginpath } }); I pass as a query in the redirect.

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

    Login Page

    No magic here you'll just notice my action upon the user being authenticated this.$router.replace(this.$route.query.from); it sends them to the query url we generated earlier.

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

    I am going to be fleshing out this logic in more detail but it works as is. I hope this helps those that come across this page.

提交回复
热议问题