Sometimes, we want to redirect to requested page after login using Vue Router.
In this article, we’ll look at how to redirect to requested page after login using Vue Router.
How to redirect to requested page after login using Vue Router?
To redirect to requested page after login using Vue Router, we can use the this.$router.push
method in our components.
For instance, we write
<script>
//...
export default {
//...
submitForm() {
await authService.login(this.credentials);
this.$router.push(this.$route.query.redirect || "/");
},
//...
};
</script>
to add the submitForm
method that calls the authService.login
method to authenticate the credentials data stored in this.credentials
.
And if authentication is succcesful, we call this.$router.push
with this.$route.query.redirect || "/"
to redirect to the redirect URL we get from the redirect
query parameter.
If redirect
query parameter doesn’t exist, then we redirect to /
.
Conclusion
To redirect to requested page after login using Vue Router, we can use the this.$router.push
method in our components.