Redirect to requested page after login using vue-router

前端 未结 8 1945
臣服心动
臣服心动 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:00

    Another quick and dirty option would be to use local storage like the following:

    1. In your beforeEach, before you redirect to login place the following line of code to save the initial requested path to local storage:

      router.js
      // If user is not authenticated, before redirecting to login
      localStorage.setItem('pathToLoadAfterLogin', from.path)

    2. Then in your login component, upon succesful login, you can redirect to the localStorage variable that you previously created:

      login.vue
      // If user login is successful, route them to what they previously requested or some default route
      this.$router.push(localStorage.getItem('pathToLoadAfterLogin') || 'somedefaultroute');

提交回复
热议问题