Redirecting to the requested page after login using vue-router

In my application, some routes are available only to authenticated users.
When an unauthenticated user clicks on the link for which he must be subscribed, he will be redirected to the login component.

If the user logs in successfully , I would like to redirect him to the URL that he requested before he was supposed to log in . However, there should also be a default route if the user did not request a different URL before logging in.

How can I achieve this with vue-router?


My code without redirection 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 to 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('/') }) 



I would really appreciate any help!

+7
redirect vuejs2 vue-router
source share
1 answer

In different ways, this can be achieved by adding a query parameter to your route when you want to redirect, and then checking when you log in if the parameter is set; If installed, you are using it or else you are backing away from root.

The code should look something like this:

Attach 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' } }); } } 

Login action

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

Hope this helps.

+3
source share

All Articles