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 redirected to the login component.
If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.
How can I achieve this using vue-router?
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('/') }) }
Redirect to login from router beforeEach() The requested path ( to. fullPath ) is assigned to the Pinia auth store property auth. returnUrl so the login page can redirect the user back their desired page after successful login.
But what if you want to redirect programmatically, without using an anchor tag at all? If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this. $router. push('www.yoursite.com/blog') .
If you are using vue-router , you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this.
Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.
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:
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*/ }) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With