Router Query Params — Transcript

Transcript of the free Vue.js lesson Router Query Paramswatch the video lesson.

In this lesson, I want to show you how to work with query parameters. Query parameters are the variables defined in the URL. Let me show you an example. As we don't have any, we can just add them directly into our URL field in the browser.

Then in our View DevTools, you can see that in the route object, we have a query object and inside of it, we have the keys destination and experience with the values of Brazil and Salvador. As you can see, we have access to the query parameters right here in our route. Query parameters can be used for many things, such as cert or filtering. Let's take a look at a real-life example.

com and search for a scroll saw. You will see in the query params Q equals scroll plus saw. Q probably stands for query here, as in the search term we are querying the database with. We don't have a search or filter in our application, but we do have a hidden flaw in our app.

Our login form will always redirect to the slash protected page, no matter which page the user actually tries to visit. So let me show you how we can fix that with query params. Please note that there are many ways to achieve this. This is just one technique.

Before we start, let's create another protected page. I'll call it invoices. over in the route file, we can now add a new route with the requires auth meta since this page requires authentication, as it wouldn't be a good idea to share our invoices with the world. And in our protected page, we can create a link to our invoices.

Let's make sure our link works. Great. What I want to do is make sure we redirect the user to the correct URL after he or she successfully logs in. There are many ways to achieve this behavior.

We could store the redirect URL in some global state, or we can use query params. If we add a redirect parameter to the URL, we could use that path instead when we're redirecting the user in our login component. There might be cases when the query parameter isn't available. So let's add support for that.

We'll set redirect path to the redirect query parameter or the protected route if it doesn't exist. Great. Let's test it in the browser. I'll try to navigate directly to invoices.

And we actually made it there just fine. That's because I forgot to put the requires all meta on the route. Let's do that real quick. Now, if I try to navigate directly to invoices, I get redirected to the login page.

As you see here, we don't have the redirect param in our URL. So our code wouldn't work as we wanted it to. Let's see what we can do about that. We can actually set the query params by setting the query property when returning the login route from the navigation guard.

fullpath. We now have the redirect param in the URL with the correct route that we want to go to. Now, once we have logged in, our invoices route goes to the right page.