Redirect to requested page after login using vue-router

前端 未结 8 1940
臣服心动
臣服心动 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 20:47

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

    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.


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

    Hope it helps.

提交回复
热议问题