Sometimes, we want to redirect to a request page after login with Vue Router.
In this article, we’ll look at how to a request page after login with Vue Router.
Redirect to Requested Page After Login Using Vue Router
We can add a redirect path to the query parameter when redirecting to the login page.
For instance, we can write:
onClick() {
if (!isAuthenticated) {
this.$router.push({ name: 'login', query: { redirect: '/profile' } });
}
}
We check for authentication credentials.
If they aren’t present, then we call this.$router.push
to redirect to the route for the login page.
The query
property has the path to redirect to when login is successful.
We have a query string with the redirect
key and the /profile
value.
Then in our login form component, we can write:
submitForm() {
login(this.credentials)
.then(() => this.$router.push(this.$route.query.redirect || '/'))
.catch(error => {
//...
})
}
in the methods
property.
We call login
which returns a promise.
So we can call then
with a callback to redirect to the path in the query string.
We get that path with the this.$route.query.redirect
property.
Then we call this.$router.push
to do the redirect.
In case it’s not defined, we redirect to the /
route.
Conclusion
We can add a redirect path to the query parameter when redirecting to the login page.